【问题标题】:Is there a trick overriding a function without a constructor in python?在python中是否有一个技巧可以覆盖没有构造函数的函数?
【发布时间】:2020-07-27 05:36:58
【问题描述】:

我在将函数从父类覆盖到子类时遇到问题...

在没有构造函数的情况下覆盖函数是否有技巧?

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

父类应该只具有函数

【问题讨论】:

  • 你从哪里知道吉普车有四个轮子?当数字 4 不在您的代码中时,您为什么期望输出?
  • 由于子类没有覆盖get_wheels,它们得到了只返回-1的超类版本。如果你把def get_wheels(self): return 4 放在Jeep 中,你就会得到你想要的。

标签: python class overriding parent-child


【解决方案1】:

更改为更准确的术语,可以在没有初始化程序的情况下对类进行子类化。事实上,object 有一个 __init__Vehicle 隐式继承自 object 所以,它就在那里。

即使超类没有__init__(),子类也可以调用super().__init__()。它最终调用object.__init__()。它不是必需的,但未来的证明代码,以防有人稍后添加到超类 init 中。但是,在您的情况下,您的子类 __init__ 不做任何事情,因此他们不需要在那里。

你的问题是你没有覆盖任何会改变轮数的东西,所以你的子类调用返回-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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多