子类无法从父类获取属性值

时间:2019-01-11 19:37:43

标签: python-3.x class encapsulation getter-setter

我有两节课。 Engine是父类,而Car是子类。 我在Engine类中定义了属性和该属性的设置器。 我想获取某个属性的值或从子类(汽车)中更改它。

这是我处理的示例:

#!/usr/bin/env python3

import sys

class Engine:
    def __init__(self):
        self.__cylinder = 4

    @property
    def cylinder(self):
        return self.__cylinder
    @cylinder.setter
    def cylinder(self,cylinder):
        self.__cylinder = cylinder

    def start(self):
        print("Engine started.")

    def stop(self):
        print("Engine stopped.")

class Car(Engine):
    def __init__(self):
        self.__wheel = 4
        print("How many cylinders? - " + str(Engine.cylinder))

    @property
    def wheel(self):
        return self.__wheel
    @wheel.setter
    def wheel(self, wheel):
        self.__wheel = wheel

    def drive(self):
        self.start()
        print("Car is driving")

    def stop(self):
        print("Car stopped")

class Tandem(Car):
    pass

def main():
    car = Car()
    #print("How many cylinders? - " + str(car.cylinder))

if __name__ == "__main__":
    main()
sys.exit(0)

Car类(初始函数)中的打印内容如下:

How many cylinders? - <property object at 0x10b754a48>

如果我取消注释主功能中的打印,则会给我错误:

Traceback (most recent call last):
  File "./test62.py", line 49, in <module>
    main()
  File "./test62.py", line 46, in main
    print("How many cylinders? - " + str(car.cylinder))
  File "./test62.py", line 11, in cylinder
    return self.__cylinder
AttributeError: 'Car' object has no attribute '_Engine__cylinder'

在这些印刷品中,我该怎么做?

0 个答案:

没有答案