如果基类不使用它们,是否可以使用@property装饰器从基类重载属性?

时间:2018-06-14 19:57:42

标签: python inheritance properties attributes decorator

首先考虑一些有效的方法:

class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        print("Getting the current voltage.")
        return self._voltage


class NorwegianBlue(Parrot):
    def __init__(self):
        super().__init__()
        self._voltage = self._voltage + 99999

    @property
    def voltage(self):
        print("Getting the current voltage.")
        return self._voltage

输出:

>>> print(Parrot().voltage)
Getting the current voltage.
100000
>>> print(NorwegianBlue().voltage)
Getting the current voltage.
199999

但是如果基类不使用装饰器怎么办?你能继承属性并仍然使用装饰器吗?显然,这不起作用:

class Parrot2:
    def __init__(self):
        self.voltage = 100000

class NorwegianBlue(Parrot2):
    def __init__(self):
        super().__init__()
        self._voltage = self.voltage + 99999

    @property
    def voltage(self):
        print("Getting the current voltage.")
        return self._voltage

输出:

>>> Parrot2().voltage
100000
>>> NorwegianBlue().voltage
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-52-88540467e120> in <module>()
----> 1 NorwegianBlue().voltage

<ipython-input-51-22a74bbd6701> in __init__(self)
      1 class NorwegianBlue(Parrot2):
      2     def __init__(self):
----> 3         super().__init__()
      4         print(self.voltage)
      5         self._voltage = self.voltage + 900000

<ipython-input-32-8e868761451b> in __init__(self)
      1 class Parrot2:
      2     def __init__(self):
----> 3         self.voltage = 100000

AttributeError: can't set attribute

1 个答案:

答案 0 :(得分:0)

这确实是可能的。正如上面的评论中指出的那样,例外是由于没有setter方法,该属性不可写。这意味着Parrot2.__init__无法初始化该属性。

以下作品:

class Parrot2:
    def __init__(self):
        self.voltage = 100000

class NorwegianBlue(Parrot2):
    def __init__(self):
        super().__init__()
        self._voltage = self.voltage + 99999

    @property
    def voltage(self):
        print("Getting the current voltage.")
        return self._voltage

    @voltage.setter
    def voltage(self, value):
        print("Setting the current voltage.")
        self._voltage = value

输出:

>>> Parrot2().voltage
100000
>>> NorwegianBlue().voltage
Setting the current voltage.
Getting the current voltage.
Getting the current voltage.
199999

感谢。