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}n'.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?
Advertisement
Answer
Class __SingletonObject
is not be instantiated
SingletonObject.instance = SingletonObject.__SingletonObject
change to
SingletonObject.instance = SingletonObject.__SingletonObject()