Python出错:AttributeError: type object 'Logger' has no attribute '_Logger__logger'
我是一个python初学者,最近编这个测试程序的时候总是跳出这个问题,求大佬们解答。模块xlogging.py:classLogger:__loggers={}def__...
我是一个python初学者,最近编这个测试程序的时候总是跳出这个问题,求大佬们解答。
模块xlogging.py:
class Logger:
__loggers = {}
def __new__(clz, name):
if name not in clz.__loggers:
logger = object.__new__(clz)
clz.__logger[name] = logger
return logger
return clz.__loggers[name]
def __init__(self, name):
if name not in vars(self):
self.name = name
def log(self, message):
print('{name} : {message}'.format(name = self.name, message = message))
xlogging_demo.py:
import xlogging
logger1 = xlogging.Logger('xlogging')
logger1.log('一些日志信息……')
logger2 = xlogging.Logger('xlogging')
logger2.log('另外一些日志信息……')
logger3 = xlogging.Logger('xlog')
logger3.log('再来一些日志信息……')
print(logger1 is logger2)
print(logger2 is logger3)
运行xlogging_demo.py时出错信息(Python版本是3.7.0):
Traceback (most recent call last):
File "C:\workspace\xlogging_demo.py", line 3, in <module>
logger1 = xlogging.Logger('xlogging')
File "C:\workspace\xlogging.py", line 6, in __new__
clz.__logger[name] = logger
AttributeError: type object 'Logger' has no attribute '_Logger__logger'
print(logger2 is logger3)
抱歉,这个问题我仔细查找了一下,发现我真是粗心,把变量名输错导致的。这个问题我已经解决了。
具体修改是把模块 xlogging.py 中 clz.__logger[name] = logger 替换为 clz.__loggers[name] = logger 即可。
希望自己以后碰到小细节的时候不要太大意,注意多检查。 展开
模块xlogging.py:
class Logger:
__loggers = {}
def __new__(clz, name):
if name not in clz.__loggers:
logger = object.__new__(clz)
clz.__logger[name] = logger
return logger
return clz.__loggers[name]
def __init__(self, name):
if name not in vars(self):
self.name = name
def log(self, message):
print('{name} : {message}'.format(name = self.name, message = message))
xlogging_demo.py:
import xlogging
logger1 = xlogging.Logger('xlogging')
logger1.log('一些日志信息……')
logger2 = xlogging.Logger('xlogging')
logger2.log('另外一些日志信息……')
logger3 = xlogging.Logger('xlog')
logger3.log('再来一些日志信息……')
print(logger1 is logger2)
print(logger2 is logger3)
运行xlogging_demo.py时出错信息(Python版本是3.7.0):
Traceback (most recent call last):
File "C:\workspace\xlogging_demo.py", line 3, in <module>
logger1 = xlogging.Logger('xlogging')
File "C:\workspace\xlogging.py", line 6, in __new__
clz.__logger[name] = logger
AttributeError: type object 'Logger' has no attribute '_Logger__logger'
print(logger2 is logger3)
抱歉,这个问题我仔细查找了一下,发现我真是粗心,把变量名输错导致的。这个问题我已经解决了。
具体修改是把模块 xlogging.py 中 clz.__logger[name] = logger 替换为 clz.__loggers[name] = logger 即可。
希望自己以后碰到小细节的时候不要太大意,注意多检查。 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询