![](/img/trans.png)
[英]Any other code doesn't run after I combined discord.py with my main script
[英]Main code in running but the other code doesn't run
我正在学习 python 中的设计模式,主题是 singleton 对象,所以我将主要代码编写为PRO003
并将其导入PRO004
。 这是PRO003
代码:
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)
这是PRO004
代码:
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)
但这是 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]
我认为这段代码想要self
,但self
没有给出,它是由 class 并且不能输入这是我的想法,但我不知道了? 这段代码有什么问题?
Class __SingletonObject
未被实例化
SingletonObject.instance = SingletonObject.__SingletonObject
改成
SingletonObject.instance = SingletonObject.__SingletonObject()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.