Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

python - Main code in running but the other code doesn't run

I am learning design pattern in python and the subject is singleton objects so, I was writing my main code as PRO003 and import it into PRO004. This is PRO003 Code:

class SingletonObject(object):
    class __SingletonObject:
        def __init__(self):
            self.name = None

        def __str__(self):
            return '{0!r} {1}'.format(self, self.name)

        def _write_log(self, level, msg):
            with open(self.name, 'a') as log_file:
                log_file.write('[{0}] -> {1}
'.format(level, msg))

        def critical(self, msg):
            self._write_log('CRITICAL', msg)

        def error(self, msg):
            self._write_log('ERROR', msg)

        def warning(self, msg):
            self._write_log('WARNING', msg)

        def info(self, msg):
            self._write_log('INFO', msg)

        def debug(self, msg):
            self._write_log('DEBUG', msg)

    instance = None

    def __new__(cls, *args, **kwargs):
        if not SingletonObject.instance:
            SingletonObject.instance = SingletonObject.__SingletonObject
        return SingletonObject.instance

    def __getattr__(self, name):
        return getattr(self.instance, name)

    def __setattr__(self, name):
        return setattr(self.instance, name)

And This is PRO004 code:

from PRO003 import SingletonObject

obj1 = SingletonObject()
obj1.name = 'logger.txt'
obj1.error('This Code Have An Error')
print('File Name: ', obj1.name, 'Object Location: ', obj1)

obj2 = SingletonObject()
obj2.name = 'logger.txt'
obj2.warning('Be Careful About This Bug')
print('File Name: ', obj2.name, 'Object Location: ', obj2)

But This Is The Output:

Traceback (most recent call last):
  File "D:PYTHON PROJECTSLEARNDesignPatternsS01PRO004.py", line 5, in <module>
    obj1.error('This Code Have An Error')
TypeError: error() missing 1 required positional argument: 'msg'
[Finished in 0.097s]

I think this code want self, but self is not giving and it is by class and it must not entered this is my idea but I do not know any more! What is the problem of this code?

question from:https://stackoverflow.com/questions/65950188/main-code-in-running-but-the-other-code-doesnt-run

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Class __SingletonObject is not be instantiated

SingletonObject.instance = SingletonObject.__SingletonObject

change to

SingletonObject.instance = SingletonObject.__SingletonObject()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...