How to call a property of the base class if this property is being overwritten in the derived class?

前端 未结 7 703
無奈伤痛
無奈伤痛 2020-11-27 14:13

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

相关标签:
7条回答
  • 2020-11-27 15:13

    try

    @property
    def bar:
        return super(FooBar, self).bar
    

    Although I'm not sure if python supports calling the base class property. A property is actually a callable object which is set up with the function specified and then replaces that name in the class. This could easily mean that there is no super function available.

    You could always switch your syntax to use the property() function though:

    class Foo(object):
    
        def _getbar(self):
            return 5
    
        def _setbar(self, a):
            print a
    
        bar = property(_getbar, _setbar)
    
    class FooBar(Foo):
    
        def _getbar(self):
            # return the same value
            # as in the base class
            return super(FooBar, self)._getbar()
    
        def bar(self, c):
            super(FooBar, self)._setbar(c)
            print "Something else"
    
        bar = property(_getbar, _setbar)
    
    fb = FooBar()
    fb.bar = 7
    
    0 讨论(0)
提交回复
热议问题