首页 > 解决方案 > 如何使用具有 __init__ 方法的子类创建一个空对象?

问题描述

我有一门课C,我用它来将许多其他课程组合在一起。当我创建self.A一个带有 child 的空对象的实例时Base,没有错误,因为class Base它没有__init__请求输入的方法。但是,我在创建空实例时遇到了问题,self.B因为它class B正在尝试__init__并且正在请求参数。

这是代码:

class Base:
    def print(self):
        print('Print useful information about the collection of classes.')


class A(Base):
    def __init__(self):
        self.print()


class B(Base):
    def __init__(self, input_1: float, input_2: float):
        self.method(input_1, input_2)

    def method(self, input_1: float, input_2: float):
        print('input 1 {} and input 2 {}'.format(input_1, input_2))


class C(B, Base):
    def __init__(self, input_master: list):
        # create an instance for the C class
        self.A = type('', (Base,), {})()
        A.__init__(self.A)
        
        self.B = type('', (B, Base), {})()      # ERROR: the child B is trying to initialize
        B.__init__(self.B, input_master[0], input_master[1])


def main():
    C([1, 2])


if __name__ == '__main__':
    main()

有没有办法创建一个空对象,它是包含初始化函数和请求参数的子类的父类?

感谢您抽出宝贵时间,如果需要更详细的描述来充分解释问题,请告诉我。

标签: pythonobject

解决方案


在我看来,您的困惑源于__init__type. 您可以动态创建新类,但在type这里您只想使用以前定义的类。每当您确实初始化此类时,您提供的参数都会传递给__init__函数,您可以在其中对它们做任何您想做的事情。

我清理了您的代码并添加了注释以澄清事情的流程:

# Create a blueprint for Base
class Base:
    def print_something(self):
        print('Something.')


# Create a blueprint for A
class A(Base):
    # Do some initialization whenever an instance of A is created.
    def __init__(self):
        print('Initializing A without any args')
        # Do some initialization
        self.answer = 42


# Create a blueprint for B
class B(Base):
    # An __init__ method with arguments
    def __init__(self, foo, bar):
        print(f'Initializing B with args: {foo}, {bar}')
        self.foo = foo
        self.bar = bar


# Create a blueprint for C
class C(B, Base):
    # Do some initialization whenever an instance of C is created.
    def __init__(self, x):
        # Create an instance of A and store it as an attribute of the instance
        # of C that we are initializing here.
        self.a = A()
        # Do the same for B, but provide init arguments.
        self.b = B(x[0], x[1])


def main():
    # Create an instance of C
    c = C([1, 2])

    # Print some attributes to clarify the hierarchy
    print(c.a.answer)
    print(c.b.foo)
    print(c.b.bar)


if __name__ == '__main__':
    main()

推荐阅读