簡體   English   中英

使用Python覆蓋屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM