[Python] Override property from wrapper class

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I have a class A with a property prop and a method method that uses this property:

    class A:
    @property
    def prop(self) -> int:
    return 1

    def method(self) -> int:
    return self.prop * 2 # Uses self.prop


    Then I have a wrapper class that tries to override this property like this:

    class B:
    def __init__(self, a: A):
    self._a = a

    @property
    def prop(self) -> int:
    return 2 # Override A's property

    def __getattr__(self, attr):
    if attr in self.__dict__:
    return getattr(self, attr)

    return getattr(self._a, attr) # Delegate attribute access to A if attr not in B


    When b.method() is called, I'd like the calculation to be done with B's prop, and get 4 as result. What is happening instead is that prop is resolving within A, and b.method() returns 2.

    b = B(a)

    b.method() # Returns 2. Wanted 4


    Is there any way I can override the property prop in A, when used on A's code, when it is being wrapped by B?

    • I can't use inheritance for these classes
    • I'd like to avoid replicating the method() logic in B
    • I also tried setting __getattribute__ in B, but it seems it is not even called when resolving prop inside A

    Continue reading...

Compartilhe esta Página