鉴于以下情况:
你知道吗父模块.py你知道吗
class ParentClass():
def __init__(self):
pass
你知道吗子模块.py你知道吗
class ChildClass(ParentClass):
def __init__(self):
pass
如果在ChildModule
中,我错误地导入了父模块而不是父类,即:
import ParentModule
而不是正确的
from ParentModule import ParentClass
我将得到以下错误:
TypeError: module.__init__() takes at most 2 arguments (3 given)
那么传递给ParentModule's __init__()
的这3个隐式参数是什么呢?ParentModule.__init__()
期望的两个参数是什么?你知道吗
如何利用这个功能?你知道吗
首先,错误消息有点误导,因为它忽略了隐式的
self
参数。可能应该说takes at most 3 arguments (4 given)
,说明self
。你知道吗如果查看模块类型的
help
输出:您将看到以下内容:
因此,模块类型的
__init__
最多应该包含3个参数:self
(未列出)、name
(模块名称)和可选的doc
(docstring)。你知道吗那不是你要传递的。当你误会的时候
Python假设
ParentModule
是一个具有奇怪元类的类,并使用type(ParentModule)
查找应该是元类的内容。它找到模块类型,并用3个参数调用它:名称('ChildClass'
)、基((ParentModule,)
)和您试图创建的新类的dict:这导致对模块类型的
__init__
的调用带有4个参数(在前面插入self
),而模块类型的__init__
不喜欢这样,因此它抛出了一个错误。你知道吗有关类创建的详细信息,请参阅Python data model documentation on metaclasses。你知道吗
导入模块时,代码将在模块中加载
__init__.py
文件。 如果您想利用init,例如预加载模块,您可以将代码添加到__init__.py
相关问题 更多 >
编程相关推荐