[英]What are the implicit arguments passed to module __init__()?
鉴于以下内容:
ParentModule.py
class ParentClass():
def __init__(self):
pass
ChildModule.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__()
什么? ParentModule.__init__()
期望的2个参数是什么?
如何利用此功能?
首先,错误消息有点误导,因为它忽略了隐式self
参数。 它应该说takes at most 3 arguments (4 given)
,占self
。
如果您查看模块类型的help
输出:
>>> import sys
>>> help(type(sys))
你会看到以下内容:
Help on class module in module builtins:
class module(object)
| module(name[, doc])
|
| Create a module object.
| ...
所以模块类型的__init__
最多需要3个参数: self
(未列出), name
(模块名称)和doc
(docstring)。
那不是你传递给它的东西。 当你错误的做
import ParentModule
class ChildClass(ParentModule)
Python假设ParentModule
是一个具有奇怪元类的类,并使用type(ParentModule)
来查找应该是元类的内容。 它找到模块类型,并使用3个参数调用它:名称( 'ChildClass'
),基数( (ParentModule,)
),以及您尝试创建的新类的dict:
type(ParentModule)('ChildClass', (ParentModule,), {'__init__': ..., ...})
这导致调用模块类型的__init__
有4个参数(在前面插入self
),而模块类型的__init__
不喜欢这样,所以它会抛出一个错误。
有关类创建细节的更多阅读,请参阅元类的Python数据模型文档 。
导入模块时,代码将在模块中加载__init__.py
文件。 如果你想使用init,例如预加载模块,你可以在__init__.py
添加代码
model/
__init__.py
func1.py
func2.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.