在 python 中是否有覆盖没有构造函数的函数的技巧?

Is there a trick overriding a function without a constructor in python?

我在将父 Class 的函数覆盖到子 Class 时遇到问题...

有无构造函数覆盖函数的技巧?

class Vehicle:
    def get_wheels(self):
        return -1

class Jeep(Vehicle):
    def __init__(self):
        super().__init__()

class Motorcycle(Vehicle):
    def __init__(self):
        super().__init__()

jeep = Jeep()
print("Jeep has", jeep.get_wheels(), "wheels")

motorcycle = Motorcycle()
print("Motorcycle has", motorcycle.get_wheels(), "wheels")

预期输出应该是

Jeep has 4 wheels
Motorcycle has 2 wheels

父代class应该只具备这个功能

更改为更准确的术语,subclass a class 没有初始值设定项是可以的。事实上,object 有一个 __init__ 并且 Vehicle 隐式继承自 object 所以,它在那里。

子class可以调用super().__init__(),即使超级class没有__init__()。它最终调用 object.__init__()。它不是必需的,但是未来的证明代码以防有人稍后添加到 super class init。然而,在你的情况下,你的 sublcass __init__ 什么都不做,所以他们不需要在那里。

你的问题是你没有覆盖任何会改变轮数的东西,所以你的 subclasses 调用 super 的方法 returns -1。相反,你可以

class Vehicle:
    def get_wheels(self):
        return -1

class Jeep(Vehicle):
    # there is no need to write an init that just calls the super's
    # init. That would happen autotmatically without this override
    #def __init__(self):
    #    super().__init__()

    # but you should override the thing you want to be different
    def get_wheels(self):
        return 4

class Motorcycle(Vehicle):
    #def __init__(self):
    #    super().__init__()
    def get_wheels(self):
        return 2

jeep = Jeep()
print("Jeep has", jeep.get_wheels(), "wheels")

motorcycle = Motorcycle()
print("Motorcycle has", motorcycle.get_wheels(), "wheels")