Python:如何从一个方法访问属性

2024-09-28 03:14:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下课程:

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__方法陷入无限递归。我理解为什么会发生这种情况,但我的问题是,如何访问日志?


Tags: 方法nameselfloginitdefargsclass
3条回答

您的__getattribute__应该从日志中排除__dict__,也可能是{}。或者,你可以做一些类似的事情

slog = StrLogger('foo')
thelog = slog._log_
do_stuff_with(slog)
print thelog

(未经测试!)在

我能想出一个办法。每当需要绕过自定义属性访问时,请使用object.__getattribute__(或任何超类)。在

class C(object):
    def __init__(self):
        self._log = []
    def __getattribute__(self, attr):
        _log = object.__getattribute__(self, '_log')
        _log.append(attr)
        return object.__getattribute__(self, attr)

>>> a = C()
>>> a.x = 1
>>> a.x
1
>>> a._log
['x', '_log']

以下略作修改的类作品:

class StrLogger(str):
    def __init__(self, *args):
        self._log_ = []
        str.__init__(self, *args)

    def __getattribute__(self, attr):
        log = str.__getattribute__(self, '_log_')
        cls = str.__getattribute__(self, '__class__')
        name = cls.__name__
        log.append((name, attr))
        return str.__getattribute__(self, attr)

s = StrLogger('abc')
print(s.title())
print(s.lower())
print(s.upper())
print(s.__dict__)

运行它会导致

^{pr2}$

相关问题 更多 >

    热门问题