使用Python覆盖属性

使用Python覆盖属性,python,inheritance,Python,Inheritance,如何在Python中覆盖属性的getter 我试着做: class Vehicule(object): def _getSpatials(self): pass def _setSpatials(self, newSpatials): pass spatials = property(_getSpatials, _setSpatials) class Car(Vehicule) def _getSpatials(self)

如何在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
但是getter调用的是车辆而不是汽车的方法


我应该更改什么?

这可能会有所帮助:

看起来您希望汽车的空间属性的getter调用Vehicleue的 空间属性的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
另一方面,从汽车的设定器内部调用汽车的设定器更加困难。 显而易见的事情是行不通的:

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)。\u setspaces

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

如果我们可以使用
vehicle
而不是
super(Car,self)
,这个问题就会容易得多。使用
super
是命令式的吗?你是什么意思?你能给我举个例子吗?我正在使用Google App Engine,Python 2.5不支持@spatials.setter语法。@Pierre:哦,好的,我将更改我的答案以使用旧语法。谢谢你。如果你想在getter中使用参数,你可以在汽车的getter中使用super(Car,self)。\u getSpatials(params)。