파이썬 점연산자 관련 스페셜 메소드 __getattribute__ 질문입니다.
조회수 449회
class Test:
def __init__(self, value):
self.objattr = value
def __getattribute__(self, name):
print("__getattribute__")
return super().__getattribute__(name)
def __getattr__(self, name):
return '속성이 없음'
obj = Test("인스턴스 속성")'
아래는 결과입니다.
__getattribute__
__getattribute__
__getattribute__
__getattribute__
__getattribute__
__getattribute__
Test 클래스로 obj인스턴스를 만들면
왜 getattribute()가 6번 실행되어
getattribute가 6번 출력되나요?
책에는 객체를 생성할 때 객체가 점 연산을 사용하므로
getattribute 메소드 내부의 print문을 실행한다고 되어 있어
이해가 안돼 질문드립니다.
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
jupyter 상에서 질문상의 코드를 테스트하면 책과 다른결과를 보게 될겁니다.
위의 코드를 py 파일로 저장한 뒤 실행해보세요.
class Test: def __init__(self, value): self.objattr = value def __getattribute__(self, name): print(f"__getattribute__ called {name.__class__}") breakpoint() return super().__getattribute__(name) def __getattr__(self, name): return '속성이 없음'
jupyter 에서는 위와 같이 수정하고 테스트 해보세요.
디버거에 의해 pdb 프롬프트가 나타나면 up 을 주고 상위 스택으로 옮긴뒤에 list 로 코드를 보세요. 호출한 것이 누군지...
ipython 내부에서 호출하고 있을 겁니다.
댓글 입력