gpt4 book ai didi

python - __init__ 函数中的 'del self.self ' 是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 22:06:11 25 4
gpt4 key购买 nike

我是这样看别人的代码的:

class SomeClass(ParentClass):
def __init__(
self,
attribute_1,
attribute_2
):
self.__dict__.update(locals())
del self.self

我能理解第一行——向ParentClass'属性字典添加新属性。但是 del self.self 是什么?

我试着看看 self.self 是什么。这正是那个 self 。为什么要删除其 __init__ 函数中的对象?当我退出 __init__ 时,我发现该对象仍然存在,地址相同。

self
Out[2]: <classname at 0x244ee3f6a90>
self.self
Out[3]: <classname at 0x244ee3f6a90>
self.self.self
Out[4]: <classname at 0x244ee3f6a90>

最佳答案

行:self.__dict__.update(locals()) 导致三个名称被绑定(bind)为 self 的属性:self属性_1属性_2del self.self 只是删除了以名称 self 命名的对象上不需要的 self 属性。

这是懒惰的。最好只使用两行:

self.attribute_1 = attribute_1
self.attribute_2 = attribute_2

关于python - __init__ 函数中的 'del self.self ' 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57366688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com