programing

기본 동작을 깨지 않고 Python에서 __getattr__을(를) 덮어쓰려면 어떻게 해야 합니까?

nicescript 2022. 12. 29. 22:04
반응형

기본 동작을 깨지 않고 Python에서 __getattr__을(를) 덮어쓰려면 어떻게 해야 합니까?

이 명령어를 덮어쓰고 싶다.__getattr__메서드를 사용하여 클래스에서 화려한 작업을 수행하지만 기본 동작을 깨고 싶지는 않습니다.

올바른 방법은 무엇입니까?

덮어쓰기__getattr__괜찮을 겁니다.__getattr__는 마지막 수단으로 호출됩니다.즉, 인스턴스에 이름에 일치하는 속성이 없는 경우에만 호출됩니다.예를 들면,foo.bar,그리고나서__getattr__이 호출되는 것은,foo라고 하는 Atribut이 없습니다.bar. 속성이 처리하지 않는 속성인 경우, 다음을 수행합니다.AttributeError:

class Foo(object):
    def __getattr__(self, name):
        if some_predicate(name):
            # ...
        else:
            # Default behaviour
            raise AttributeError

단, 와는 달리__getattr__,__getattribute__먼저 호출됩니다(오브젝트에서 상속된 새로운 스타일 클래스에서만 사용 가능).이 경우 다음과 같이 기본 동작을 유지할 수 있습니다.

class Foo(object):
    def __getattribute__(self, name):
        if some_predicate(name):
            # ...
        else:
            # Default behaviour
            return object.__getattribute__(self, name)

자세한 내용은 Python 문서를 참조하십시오.

class A(object):
    def __init__(self):
        self.a = 42

    def __getattr__(self, attr):
        if attr in ["b", "c"]:
            return 42
        raise AttributeError("%r object has no attribute %r" %
                             (self.__class__.__name__, attr))

>>> a = A()
>>> a.a
42
>>> a.b
42
>>> a.missing
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __getattr__
AttributeError: 'A' object has no attribute 'missing'
>>> hasattr(a, "b")
True
>>> hasattr(a, "missing")
False

마이클 답변을 연장하려면 다음을 사용하여 기본 동작을 유지하려면__getattr__, 다음과 같이 할 수 있습니다.

class Foo(object):
    def __getattr__(self, name):
        if name == 'something':
            return 42

        # Default behaviour
        return self.__getattribute__(name)

이제 예외 메시지가 더 자세히 설명됩니다.

>>> foo.something
42
>>> foo.error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __getattr__
AttributeError: 'Foo' object has no attribute 'error'

언급URL : https://stackoverflow.com/questions/2405590/how-do-i-override-getattr-in-python-without-breaking-the-default-behavior

반응형