我正在将我的一些类从广泛使用的getter和setter更改为更具Python风格的属性。
但是现在我遇到了困难,因为我的一些先前的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
Foo.bar.fset(self, c)
?为什么不是Foo.bar.fset(c)
- 没有"self" - 我以为这是隐式传递的? - nerdocself
是从链式调用Foo.bar.fset
中推断出来的吗? - Tadhg McDonald-Jensenfoo = Foo()
\foo.bar(c)
,没有self被传递,但是*bar()*从Python中接收它。我不是Python专家,更多的是一个初学者。这只是一个想法。 - nerdocself
is only implicitly passed when the method is called on an instance of a class. For example, if I have a classA
with a methodb(self, arg)
, and I create an instancec = A()
, then callingc.b(arg)
is equivalent toA.b(c, arg)
- TallChuckFoo
就是self.__class__.__bases__[0]
(对于super(self.__class__.__bases__[1], self)
也是一个方便的技巧)。 - Matteo Ferla