파이썬[Python]: 내장함수 - __getattribute__ 메서드

파이썬(Phthon): 내장함수 - __getattribute__ 메서드(method)


/// 설명

클래스의 인스턴스에서 속성(attribute)에 접근하고자 할 경우 호출 됩니다.
클래스의 속성을 직접 반환하면 recursion 이 발생합니다. object.__getattribute__(self, name) 필요
ex) a.string -> __getattribute__ 호출 -> return self.string -> __getattribute__ 호출 -> return self.string -> ...

참고: __getattr__()

※ 형식
object.__getattribute__(self, name)

reference
https://docs.python.org/3/reference/datamodel.html

/// 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class A:
    def __init__(self, string):
        self.string = string
 
    def __getattribute__(self, name):
        try:
            attribute = super(A, self).__getattribute__(name)
            return attribute
        except AttributeError as e:
            print(e)
 
 
= A('This is a string')
print(a.__dict__)  # {'string': 'This is a string'}
print(a.string)  # This is a string
print(getattr(a, 'string'))  # This is a string
print(a.str)  # 'A' object has no attribute 'str'
              # None
 
cs

* 실행환경: Microsoft Windows 10 Homes
* 인터프리터: 파이썬(Python 3.9)


– 당신을 응원합니다. –

댓글

이 블로그의 인기 게시물

파이썬[Python]: 내장함수 - from_bytes 메서드

파이썬[Python]: 내장함수 - __len__ 메서드

파이썬[Python]: kivy - 한글 사용

C 언어: sin 함수, cos 함수, tan 함수

파이썬[Python]: 내장함수 - bit_length 메서드