gpt4 book ai didi

python - 为什么 `obj.method is obj._class__method` 是错误的

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:02 25 4
gpt4 key购买 nike

我正在阅读 python 类的文档,我遇到了 9.6。有写的私有(private)变量

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

这让我很好奇 obj.update is obj._Mapping__update 应该返回 True。但事实并非如此。我检查了他们两个的ID,他们是一样的。那么...这里发生了什么?

In [1]: class Mapping: 
...: def __init__(self, iterable):
...: self.items_list = []
...: self.__update(iterable)
...:
...: def update(self, iterable):
...: for item in iterable:
...: self.items_list.append(item)
...:
...: __update = update # private copy of original update() method
...:

In [2]: obj = Mapping([])

In [3]: obj.update == obj._Mapping__update
Out[3]: True

In [4]: print(id(obj.update), id(obj._Mapping__update))
139655901847816 139655901847816

In [5]: obj.update is obj._Mapping__update
Out[5]: False

最佳答案

当您访问实例的方法时,每次都会返回一个绑定(bind)方法:

>>> class X:
... def foo(self): pass
... __foo = foo
...
>>> inst = X()
>>> a = inst.foo
>>> b = inst._X__foo
>>> a
<bound method X.foo of <__main__.X object at 0x7f62f41144a8>>
>>> b
<bound method X.foo of <__main__.X object at 0x7f62f41144a8>>

这两个对象将比较相等(因为它们引用相同的底层方法),但它们不会具有相同的身份:

>>> a == b, id(a), id(b), a is b
(True, 140062981356744, 140062980414856, False)

请注意,如果您在属性上直接调用 id() ,每次都会创建并丢弃一个新的绑定(bind)方法,并且不能保证 Python不会重复使用以前的 ID。因此,在进行此类比较之前将对象保存到变量中很重要。

要比较底层方法的身份,您应该使用类:

>>> X._X__foo is X.foo
True

关于python - 为什么 `obj.method is obj._class__method` 是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57103713/

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