`Python 2.7中的id`function,`is`operator,object identity和userdefined方法

2024-06-26 07:28:11 发布

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

Python 2.7中下面代码的结果让我觉得很矛盾。应该使用is运算符处理对象标识,也应该使用id。但当我在看一个用户定义的方法时,它们的结果是不同的。为什么?

py-mach >>class Hello(object):
...  def hello():
...    pass
...
py-mach >>Hello.hello is Hello.hello
False
py-mach >>id(Hello.hello) - id(Hello.hello)
0

我发现下面对Python data model的描述的摘录有些用处。但这并没有真正说明一切。如果每次重新构造用户定义的方法对象,为什么id函数返回相同的整数?

User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object, an unbound user-defined method object, or a class method object. When the attribute is a user-defined method object, a new method object is only created if the class from which it is being retrieved is the same as, or a derived class of, the class stored in the original method object; otherwise, the original method object is used as it is.


Tags: ofthepyanidhelloobjectis