python properties and inheritance

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

    I don't agree that the chosen answer is the ideal way to allow for overriding the property methods. If you expect the getters and setters to be overridden, then you can use lambda to provide access to self, with something like lambda self: self..

    This works (at least) for Python versions 2.4 to 3.6.

    If anyone knows a way to do this with by using property as a decorator instead of as a direct property() call, I'd like to hear it!

    Example:

    class Foo(object):
        def _get_meow(self):
            return self._meow + ' from a Foo'
        def _set_meow(self, value):
            self._meow = value
        meow = property(fget=lambda self: self._get_meow(),
                        fset=lambda self, value: self._set_meow(value))
    

    This way, an override can be easily performed:

    class Bar(Foo):
        def _get_meow(self):
            return super(Bar, self)._get_meow() + ', altered by a Bar'
    

    so that:

    >>> foo = Foo()
    >>> bar = Bar()
    >>> foo.meow, bar.meow = "meow", "meow"
    >>> foo.meow
    "meow from a Foo"
    >>> bar.meow
    "meow from a Foo, altered by a Bar"
    

    I discovered this on geek at play.

提交回复
热议问题