python properties and inheritance

后端 未结 10 1462
粉色の甜心
粉色の甜心 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:29

    Another way to do it, without having to create any additional classes. I've added a set method to show what you do if you only override one of the two:

    class Foo(object):
        def _get_age(self):
            return 11
    
        def _set_age(self, age):
            self._age = age
    
        age = property(_get_age, _set_age)
    
    
    class Bar(Foo):
        def _get_age(self):
            return 44
    
        age = property(_get_age, Foo._set_age)
    

    This is a pretty contrived example, but you should get the idea.

提交回复
热议问题