python - 使用 Python 覆盖属性

标签 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):
        spatials = super(Car, self).spatials()
        return spatials

但是 getter 调用的是 Vehicule 的方法而不是 Car 的方法。

我应该改变什么?

最佳答案

看起来您希望 Car 的空间属性的 getter 调用 Vehicule 的 空间属性的 setter/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 的 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 - 使用 Python 覆盖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4107988/

相关文章:

python - 从文件夹重新加载模块?

python - Tkinter - 尽管保留全局引用,但图像不会显示在按钮上

javascript - Node.js + Python 子进程 : Print returns data, 但没有返回

c# - 无法直观地更改继承形式的 DataGridView

C#模板类型继承

Java : Inheritance and Basic Design Optimization

java - 多态性最佳实践

python - 在python中合并df

python - 根据 django 网站上的操作显示用户上个月的进度

c++ - 模板模板成员继承 'using'