2012-06-21 4 views
4

__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__')]} 
관련 문제