【问题标题】:How to initialize a parent class with a child object outside of the child's __init__ function如何在子类的 __init__ 函数之外使用子对象初始化父类
【发布时间】:2023-02-02 22:46:37
【问题描述】:

我们有两个基础班。

class A:
    def __init__(self) -> None:
        pass
        
        
class B(A):
    def __init__(self) -> None:
        print(self)
        A.__init__(self)

在初始化B的时候,可以看到传递给A的“self”是B对象的一个​​实例。

a = A()
b = B()

>> <__main__.B object at 0x0000021CC0E39700>

现在,如果我们打印 b,我们可以看到它也是 B 对象实例的实例。但是,A 不能用 B 之外的 B 实例初始化。

print(b)
A(b)

>> TypeError: __init__() takes 1 positional argument but 2 were given

这里将是无:

b = B()
a = A.__init__(b)

那怎么办?

【问题讨论】:

  • 你到底想用这个来完成什么?您是要为子类运行父类的初始化代码,还是要创建具有子类属性的父类实例?目前尚不清楚您的目标是什么。
  • 这里的目标是什么。一个类不需要子类被初始化

标签: python


【解决方案1】:

我认为这是不可能的。 这里的要点是,在调用一个类的构造函数时,python 将在内存中创建该类的一个新实例,然后将这个新对象以及所有附加参数传递给__init__(self, *args, **kwargs)

所以通过调用A(b),你实际上是在调用一个__init__方法,它有一个额外的参数,即__init__(self, b)

【讨论】:

    【解决方案2】:

    你可以使用super来做到这一点

    class A:
        def __init__(self):
            print("__init__ from A")
            self.a = 1
    
    class B(A):
        def __init__(self):
            print("__init__ from B")
            self.b = 2
    
    b = B()
    super(type(b), b).__init__()
    print(b.a)
    

    输出

    __init__ from B
    __init__ from A
    1
    

    理想情况下,您应该在派生类方法中处理所有父类方法调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      相关资源
      最近更新 更多