![](/img/trans.png)
[英]Python AttributeError: property cannot overwrite inherited attribute?
[英]Overwrite property using Python
你如何在Python中覆盖属性的getter?
我试过这样做:
class Vehicule(object):
def _getSpatials(self):
pass
def _setSpatials(self, newSpatials):
pass
spatials = property(_getSpatials, _setSpatials)
class Car(Vehicule)
def _getSpatials(self):
spatials = super(Car, self).spatials()
return spatials
但吸气剂是调用Vehicule而不是Car的方法。
我应该改变什么?
看起来你想要Car的空间属性的吸气剂来调用Vehicule的空间属性的吸气剂。 你可以实现这一目标
class Vehicule(object):
def __init__(self):
self._spatials = 1
def _getSpatials(self):
print("Calling Vehicule's spatials getter")
return self._spatials
def _setSpatials(self,value):
print("Calling Vehicule's spatials setter")
self._spatials=value
spatials=property(_getSpatials,_setSpatials)
class Car(Vehicule):
def __init__(self):
super(Car,self).__init__()
def _getSpatials(self):
print("Calling Car's spatials getter")
return super(Car,self).spatials
spatials=property(_getSpatials)
v=Vehicule()
c=Car()
print(c.spatials)
# Calling Car's spatials getter
# Calling Vehicule's spatials getter
# 1
另一方面,从Car的setter中调用Vehicule的setter更加困难。 显而易见的事情不起作用:
class Car(Vehicule):
def __init__(self):
super(Car,self).__init__()
def _getSpatials(self):
print("Calling Car's spatials getter")
return super(Car,self).spatials
def _setSpatials(self,value):
print("Calling Car's spatials setter")
super(Car,self).spatials=value
spatials=property(_getSpatials,_setSpatials)
v=Vehicule()
c=Car()
print(c.spatials)
c.spatials = 10
AttributeError: 'super' object has no attribute 'spatials'
相反,诀窍是调用super(Car,self)._setSpatials
:
class Car(Vehicule):
def __init__(self):
super(Car,self).__init__()
def _getSpatials(self):
print("Calling Car's spatials getter")
return super(Car,self).spatials
def _setSpatials(self,value):
print("Calling Car's spatials setter")
super(Car,self)._setSpatials(value)
spatials=property(_getSpatials,_setSpatials)
v=Vehicule()
c=Car()
print(c.spatials)
# Calling Car's spatials getter
# Calling Vehicule's spatials getter
# 1
c.spatials = 10
# Calling Car's spatials setter
# Calling Vehicule's spatials setter
print(c.spatials)
# Calling Car's spatials getter
# Calling Vehicule's spatials getter
# 10
这可能会有所帮助: python属性和继承
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.