2012-06-21 34 views
4

我有下面的类访问属性:的Python:如何从一个__getattribute__方法

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

回答

1

您的__getattribute__应该排除__dict__,也可能排除_log_。或者,你可以不喜欢

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

(未经测试!)

+0

谢谢!我现在看到递归是由于在日志记录过程中访问'_log_'造成的。它还令我困惑,当其他属性被访问时,日志本身就起作用。 – Matt

3

我能想到的一种方式。使用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'] 
2

以下略作修改类的工作:

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__) 

运行它导致

Abc 
abc 
ABC 
{'_log_': [('StrLogger', 'title'), ('StrLogger', 'lower'), ('StrLogger', 'upper'), ('StrLogger', '__dict__')]} 
相关问题