【问题标题】:Calling Parent Constructor on Subclass instance在子类实例上调用父构造函数
【发布时间】:2018-01-22 16:25:34
【问题描述】:

如果我没记错的话,在 C++ 中,可以在子类的实例上调用父类的构造函数,这样就会创建父类的实例,这样只会复制重叠的属性。 python 中是否存在这样的功能,使得下面的“python”代码会做同样的事情?

如果我有一个父类 Fruit

class Fruit():
    def __init__(self, color):
        self.color = color

还有一个子类 Apple

class Apple(Fruit):
    def __init__(self, color, seeds):
        self.seeds = seeds
        super().__init__(color)

你可以的

an_apple = Apple('red', 42)
a_fruit = Fruit(an_apple)

然后得到一个红色水果。

【问题讨论】:

  • 在 C++ 中,父构造函数首先被调用...自动。
  • 您的前两个代码块似乎正是您想要的。第三块没有意义!我怀疑您正在考虑基类的复制构造函数。
  • 我不知道你的 c++ sn-p 想要做什么,但我怀疑它不会实现你想要的。
  • @FrançoisAndrieux 对此感到抱歉,我已经删除了标签并澄清了一点
  • @quamrana 这正是我的问题! :) 有没有真正有意义的功能?

标签: python inheritance constructor


【解决方案1】:

我唯一能想到的就是做一个工厂方法:

class Fruit():
    def __init__(self, color):
        self.color = color
    @staticmethod
    def MakeFruit(aFruit):
        return Fruit(aFruit.color)

用法:

an_apple = Apple('red', 42)  #assuming Apple as before
a_fruit = Fruit('blue')
a_red_fruit = Fruit.MakeFruit(an_apple)

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2013-08-27
    • 2013-09-25
    • 2014-08-11
    相关资源
    最近更新 更多