2010-11-05 131 views
6

如何覆蓋Python中屬性的getter?使用Python覆蓋屬性

我試圖做的事:

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的方法,而不是汽車。

我應該改變什麼?

+0

這個問題將是一個容易得多,如果我們可以用'Vehicule',而不是'超(汽車,個體經營)'。是否使用「超級」命令? – unutbu 2010-11-05 18:15:25

+0

你是什麼意思?你可以給我一個例子嗎 ? – 2010-11-05 18:37:41

回答

3

它看起來像你想要租車的空間屬性的getter調用驅動車輛的 空間屬性的getter。您可以通過

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的二傳手中調用Vehicule的二傳手更加困難。 顯而易見的事情不工作:

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 
+0

我正在使用Google App Engine,並且不支持@ spatials.setter語法。 – 2010-11-05 19:19:17

+0

@Pierre:哦,好吧,我會改變我的答案,使用舊的語法。 – unutbu 2010-11-05 19:31:05

+0

謝謝unutbu。如果你想在getter中使用參數,你可以在Car中的getter中使用super(Car,self)._ getSpatials(params)。 – 2010-11-05 20:07:38