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 The Out 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 PROJECTS\LEARN\DesignPatterns\S01\PRO004.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 ? Help Me ! Thank you !!!
Aucun commentaire:
Enregistrer un commentaire