理解/使用 dict 的 __init__ 方法

Understanding / Using __init__ method of dict

我想到了如何使 Python class 可序列化。

class FileItem(dict):
    def __init__(self, name):
        dict.__init__(self, name=name)

x = FileItem("test")
print(x)

{'name': 'test'}

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

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

这会导致以下错误:

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

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

__new__ creates new instances but __init__用于初始化新创建的实例,因此__init__需要实例才能使用。

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

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

不同之处在于 self 属性 未通过,__init__ 属性 将其计算应用于已通过的实例 (self)其中,如果 __init__ 函数没有任何上下文,它会抛出一个错误
祝你有美好的一天,卢卡斯。

因此,请注意您没有为 __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__ returns None:

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

因为__init__不是构造器,而是初始化器。在 Python 中,这是对象初始化过程中的两个不同步骤。

“构造器”是__new__:

>>> dict.__new__(dict)
{}

Read about it 在 Python 数据模型文档中。

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

x = dict.__new__(dict)

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

>>> type.__call__(dict)
{}