为什么每次访问都会更改 Python 2 中未绑定方法的 id() [英] Why does id() of an unbound method in Python 2 change for every access

查看:32
本文介绍了为什么每次访问都会更改 Python 2 中未绑定方法的 id()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.6.5(r265:79063,2012 年 10 月 1 日,22:07:21)[海湾合作委员会 4.4.3]

<预><代码>>>>我的班级:... def func(self):... 经过>>>dd = myclass.func>>>ee = myclass.func>>>cc = myclass.func>>>ff = myclass.func>>>ss = myclass.func>>>uu = myclass.func>>>pp = myclass.func>>>>>>>>>id(dd) ;身份证(抄送);id(ee) ;id(ff) ;身份证(ss);id(uu) ;编号(pp)3074535252L3074534772L3074522444L3074531732L3074497588L3073003604L3073003724L

为什么每次绑定的方法的ID都不一样?

不应该是一样的吗?

解决方案

这是因为类(旧的或新的)上的方法实际上就像使用描述符 __get__ 方法的属性一样;在python 2上的代码

foo = FooClass.bar_method

类似于

导入类型foo = types.MethodType(FooClass.__dict__['bar_method'], None, FooClass)

它会在每次访问时创建一个 instancemethod(bar_method, None, FooClass) 的新实例.原始函数作为FooClass.bar_method.im_funcfoo.im_class 中的类实例可用.绑定和未绑定方法的类型是相同的instancemethod;如果 im_self 成员是 None,则 instancemethod 实例具有 repr ,而如果 im_self 成员不是 None,则表示是

Python 3 不同.未绑定的方法在 0x7fd419cf69e0> 处有一个 repr 并且 id 始终相同,也就是说它们只是通用函数.在 Python 3 中,您可以为未绑定的未修饰方法的 self 传递任何内容,甚至是 None,它只是一个名称中带有点的函数.

Python 2.6.5 (r265:79063, Oct 1 2012, 22:07:21) [GCC 4.4.3]

>>> class myclass:
...     def func(self):
...             pass

>>> dd = myclass.func
>>> ee = myclass.func
>>> cc = myclass.func
>>> ff = myclass.func
>>> ss = myclass.func
>>> uu = myclass.func
>>> pp = myclass.func
>>> 
>>> 
>>> id(dd) ; id(cc) ; id(ee) ; id(ff) ; id(ss) ; id(uu) ; id(pp)
3074535252L
3074534772L
3074522444L
3074531732L
3074497588L
3073003604L
3073003724L

Why is the ID of the unbound method different each time?

Shouldn't it be same ?

解决方案

This is because the methods on a class (old or new) work really like attributes with the descriptor __get__ method; On python 2 the code

foo = FooClass.bar_method

is analogous to

import types
foo = types.MethodType(FooClass.__dict__['bar_method'], None, FooClass)

It will create a new instance of instancemethod(bar_method, None, FooClass) on each access. The original function is available as FooClass.bar_method.im_func and the class instance in foo.im_class. The type for both bound and unbound methods is the same instancemethod; if the im_self member is None, the instancemethod instance has the repr <unbound method ...>, whereas if im_self member is not None, the repr is <bound method...>

Python 3 is different. Unbound methods have a repr <function x.f at 0x7fd419cf69e0> and the id is always the same, that is they are just general functions. In Python 3 you can pass anything for self of an unbound undecorated method, even None, it is just a function with a dot in its name.

这篇关于为什么每次访问都会更改 Python 2 中未绑定方法的 id()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆