我有以下课程:
class StrLogger(str):
def __init__(self, *args):
self._log_ = []
str.__init__(self, *args)
def __getattribute__(self, attr):
self._log_.append((self.__name__, attr))
return str.__getattribute__(self, attr)
我可以用slog = StrLogger('foo')
初始化一个StrLogger
,我可以从str
访问它继承的所有方法,它运行起来没有问题。问题是,当我试图用slog._log_
或slog.__dict__['_log_']
检索日志时,__getattribute__
方法陷入无限递归。我理解为什么会发生这种情况,但我的问题是,如何访问日志?
您的}。或者,你可以做一些类似的事情
__getattribute__
应该从日志中排除__dict__
,也可能是{(未经测试!)在
我能想出一个办法。每当需要绕过自定义属性访问时,请使用
object.__getattribute__
(或任何超类)。在以下略作修改的类作品:
运行它会导致
^{pr2}$相关问题 更多 >
编程相关推荐