gpt4 book ai didi

windows - 为什么对象的 id 会根据 python shell 中的行而改变

转载 作者:可可西里 更新时间:2023-11-01 10:26:33 25 4
gpt4 key购买 nike

这个问题只是出于好奇。

当我阅读 python's object model documentation 时,我决定对类方法的 id 进行一些试验,发现了这种行为:

 Python 3.2.2 (default, Sep  4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class A():
def a(self):
pass


>>> id(A().a)
54107080
>>> id(A().a)
54108104
>>> id(A().a)
54107080
>>> id(A().a)
54108104
>>>
>>> id(A().a)
54108104
>>>
>>> id(A().a)
54108104
>>> id(A().a)
54107080
>>>

方法的id随着线路的奇偶校验而变化!

其实我想创建几个同一个类的实例,看看它们是否有相同的方法对象,我希望它们是完全相同的,或者每次都改变,但我没想到的是方法 id 将与解释器行是否偶数相关!有什么想法吗?

注意:我知道文档和解释器的版本不匹配,碰巧我在 Windows 上并且我只安装了 3.2

最佳答案

我将解释 id(A().a) 行的作用:

A() # creates a new object I call a

然后

A().a # creates a function f bound to a
A.a.__get__(A(), A) # same as above

>>> A.a.__get__(A(), A)
<bound method A.a of <__main__.A object at 0x02D85550>>
>>> A().a
<bound method A.a of <__main__.A object at 0x02D29410>>

这个绑定(bind)函数总是另一个,因为它在 __self__ 中有另一个对象

>>> a = A()
>>> assert a.a.__self__ is a

__self__ 将作为第一个参数 self 传递给函数 A.a

编辑:这是它的样子:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class A:
def a(self):
pass


>>> id(A().a)
43476312
>>> id(A().a)
49018760

这里id像abab一样重复

Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class A:
def a(self):
pas
s


>>> id(A().a)
50195512
>>> id(A().a)
50195832
>>> id(A().a)
50195512
>>> id(A().a)
50195832

编辑:对于 linux 或不是我的机器以及我不知道的任何东西

id(A().a)

将始终给出相同的结果,除非您将其存储到变量中。我不知道为什么,但我认为这是因为性能优化。对于堆栈上的对象,您无需在每次调用函数时都为对象分配新空间。

关于windows - 为什么对象的 id 会根据 python shell 中的行而改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15315096/

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