python properties and inheritance

后端 未结 10 1460
粉色の甜心
粉色の甜心 2020-12-12 18:06

I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:

class Foo(object):
    d         


        
10条回答
  •  执笔经年
    2020-12-12 18:38

    A possible workaround might look like:

    class Foo:
        def __init__(self, age):
            self.age = age
    
        @property
        def age(self):
            print('Foo: getting age')
            return self._age
    
        @age.setter
        def age(self, value):
            print('Foo: setting age')
            self._age = value
    
    
    class Bar(Foo):
        def __init__(self, age):
            self.age = age
    
        @property
        def age(self):
            return super().age
    
        @age.setter
        def age(self, value):
            super(Bar, Bar).age.__set__(self, value)
    
    if __name__ == '__main__':
        f = Foo(11)
        print(f.age)
        b = Bar(44)
        print(b.age)
    

    It prints

    Foo: setting age
    Foo: getting age
    11
    Foo: setting age
    Foo: getting age
    44
    

    Got the idea from "Python Cookbook" by David Beazley & Brian K. Jones. Using Python 3.5.3 on Debian GNU/Linux 9.11 (stretch)

提交回复
热议问题