在子类 __init__ 中覆盖超类变量,然后对变量使用超类方法不使用更新的子类值 python

问题描述 投票:0回答:0

模块文件

class Car:
    def __init__(self):
        self.distance = 2
        self.__horn = "beep beep"
        self.__color = ""
        self.__line = "-"

    def soundHorn(self):
        print(self.__horn)

    def getColor(self):
        return self.__color

class Model_2(Car):
    def __init__(self):
        super(Model_2, self).__init__()
        self.__color = "red"
        self.__horn = "honk honk"

    def getColor(self):
        return self.__color
import moduletest as module

def main():
    computerCar = module.Model_2()

    computerCar.soundHorn()

if __name__ == "__main__":
    main()

调用computerCar.soundHorn()时打印的是beep beep,但应该是打印honk honk。为什么 soundHorn() 方法使用超类 init 中提供的默认值,而不是我在子类中给它的覆盖值?

我原以为 computerCar.soundHorn() 会打印 honk honk,但它会打印 beep beep。

python inheritance subclass super
© www.soinside.com 2019 - 2024. All rights reserved.