【发布时间】:2018-10-25 00:36:39
【问题描述】:
我实际上是在浏览descriptors python 文档并遇到了这个例子
>>> class D(object):
def f(self, x):
return x
>>> d = D()
>>> D.__dict__['f'] # Stored internally as a function
<function f at 0x00C45070>
>>> id(D.__dict__['f']) # Memory location
49294384
>>> D.f # Get from a class becomes an unbound method
<unbound method D.f>
>>> id(D.f )
48549440
>>> d.f # Get from an instance becomes a bound method
<bound method D.f of <__main__.D object at 0x00B18C90>>
>>> id(d.f)
48549440
所以从上面的代码中,我了解到python将一个类的function definition/declaration作为一个单独的对象存储在类__dict__变量内部,当我们直接使用__dict__变量访问时,它的内存位置为49294384
但是为什么当通过Class or Object? 访问时,它显示为具有不同memory location 48549440 的不同函数/方法对象,例如D.f and d.f
当我们使用__dict__ 变量访问时,它不应该引用同一个对象吗?如果有,为什么?
【问题讨论】:
-
您的代码来自 Python 2,但您链接到的文档是 Python 3。Python 3 中不再存在“未绑定方法”。
-
@DanielRoseman,很抱歉,我使用的是 Python 2.7,但即使文档中的代码也是一样的
标签: python function class object