传递给模块init()的隐式参数是什么?

2024-06-26 14:48:56 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于以下情况:

你知道吗父模块.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__()期望的两个参数是什么?你知道吗

如何利用这个功能?你知道吗


Tags: 模块pyimportself参数initdef错误
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 data model documentation on metaclasses。你知道吗

导入模块时,代码将在模块中加载__init__.py文件。 如果您想利用init,例如预加载模块,您可以将代码添加到__init__.py

model/
    __init__.py
    func1.py
    func2.py

相关问题 更多 >