理解/使用dict的__init__方法



我发现了如何使Python类可序列化的想法。

class FileItem(dict):
def __init__(self, name):
dict.__init__(self, name=name)
x = FileItem("test")
print(x)
{'name': 'test'}

这很好用,但我不明白怎么做。我认为dict.__init__从dict类调用__init__方法来创建一个新实例,所以我希望它能起作用:

x = dict.__init__(name="test")

这会导致以下错误:

TypeError: descriptor '__init__' of 'dict' object needs an argument

为什么这与上面的例子不同?

因此,请注意,您没有为__init__、提供第二个参数

>>> x = dict.__init__(name="test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor '__init__' of 'dict' object needs an argument

它需要实例,即self作为第一个参数。当然,如果您创建一个合适的实例并传递该实例,__init__将返回None:

>>> x = dict.__init__({}, name="test")
>>> print(x)
None

因为__init__不是构造函数,所以它是一个初始值设定项。在Python中,这是对象初始化过程中的两个不同步骤。

";构造函数";是__new__:

>>> dict.__new__(dict)
{}

请参阅Python数据模型文档中的相关内容。

此外,为了体面起见,你可能不应该洒:

x = dict.__new__(dict)

在真实代码中。但这就是它的机制。顺便说一句,所有这些都发生在type.__call__中。type是创建类的父类,一个元类。(它本身也是一种类型…type(type) is type就像type(dict) is type…(

>>> type.__call__(dict)
{}

__new__创建新实例,但__init__用于初始化新创建的实例,因此__init__需要使用一个实例。

当您执行dict.__init__(name='test')时,它不会在任何实例上运行,因此会出现错误。另一方面,对于dict.__init__(self, name=name),您确实将实例self作为参数传递,因此它可以工作。

通常,您会使用super().__init__(name=name),它负责提供self作为参数,并且在您稍后决定更改基类时也可以使用。

不同之处在于未传递的self属性,__init__属性将其计算应用于传入的实例(self(,如果__init__函数没有任何上下文,则会抛出错误
祝你今天愉快,Lukas。

最新更新