python properties and inheritance

后端 未结 10 1465
粉色の甜心
粉色の甜心 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条回答
  •  Happy的楠姐
    2020-12-12 18:51

    Something like this will work

    class HackedProperty(object):
        def __init__(self, f):
            self.f = f
        def __get__(self, inst, owner):    
            return getattr(inst, self.f.__name__)()
    
    class Foo(object):
        def _get_age(self):
            return 11
        age = HackedProperty(_get_age)
    
    class Bar(Foo):
        def _get_age(self):
            return 44
    
    print Bar().age
    print Foo().age
    

提交回复
热议问题