python - 如何使用具有 __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()
有没有办法创建一个空对象,它是包含初始化函数和请求参数的子类的父类?
感谢您抽出宝贵时间,如果需要更详细的描述来充分解释问题,请告诉我。
解决方案
在我看来,您的困惑源于__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()
推荐阅读
- javascript - 名称未定义但检查员显示
- r - 区域统计计算像素份额并确定 R 中最频繁的类
- python - 请求 API 但返回空,为什么?
- c# - 在 C# 中遵循给定单元测试时,如何正确删除从 void functionR emove 中的列表 ILine 继承接口的对象?
- c# - .Net BackgroundService 在多服务器环境中
- numpy - 带有二维数组的 Numpy 花式索引 - 解释
- c# - 将文件从 Azure 读入 MemoryStream C#
- javascript - 在选中复选框时,需要另一个复选框
- python - 如何刮除所有元素而不仅仅是一个?
- visual-studio - 如何在 Line and Stacked Chart Power BI 中将阶梯线区域扩展到图形边缘