[Python] How to call a property of the base class if this property is being overwritten in the...

Discussão em 'Python' iniciado por Stack, Junho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.

    But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties? How to call the property getter or setter in the parent class?

    Of course just calling the attribute itself gives infinite recursion.

    class Foo(object):
    @property
    def bar(self):
    return 5

    @bar.setter
    def bar(self, a):
    print(a)


    class FooBar(Foo):
    @property
    def bar(self):
    # return the same value
    # as in the base class
    return self.bar # --> recursion!

    @bar.setter
    def bar(self, c):
    # perform the same action
    # as in the base class
    self.bar = c # --> recursion!
    # then do something else
    print('something else')


    fb = FooBar()
    fb.bar = 7

    Continue reading...

Compartilhe esta Página