如果派生类中的基类属性被覆盖,该如何调用基类的属性?
我正在将我的某些类从对getter和setter的广泛使用改为对属性的更pythonic的使用。
但是现在我陷入了困境,因为以前的一些getter或setter方法会调用基类的相应方法,然后执行其他操作。但是如何通过属性来实现呢?如何在父类中调用属性getter或setter?
当然,仅调用属性本身即可进行无限递归。
class Foo(object):
@property
def bar(self):
return 5
@bar.setter
def bar(self, a):
print a
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return self.bar # --> recursion!
@bar.setter
def bar(self, c):
# perform the same action
# as in the base class
self.bar = c # --> recursion!
# then do something else
print 'something else'
fb = FooBar()
fb.bar = 7
-
您可能认为您可以调用由属性调用的基类函数:
class FooBar(Foo): @property def bar(self): # return the same value # as in the base class return Foo.bar(self)
尽管我认为这是最明显的尝试- 它不起作用,因为bar是属性,而不是可调用的。
但是属性只是一个对象,使用getter方法可以找到相应的属性:
class FooBar(Foo): @property def bar(self): # return the same value # as in the base class return Foo.bar.fget(self)