数值的加减会改变python中id_为什么对象的id会根据python shell中的行而改变

This questions is just out of curiosity.

While I was reading the python's object model documentation, I decided to experiment a little with the id of a class method and found this behavior:

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

>>>

The id of the method changes with the parity of the line!

I actually wanted to create a couple of instances of the same class and see if they had the same method object, and I expected that they would be the exact same one, or change every time, what I did not expect was that the method id would be related with the interpreter line being even or not! Any ideas?

Note: I know that there is a mismatch of version from the docs and the interpreter, it just happens that I'm on windows and I have only 3.2 installed

解决方案

I will explain wat the line id(A().a) does:

A() # creates a new object I call a

Then

A().a # creates a function f bound to a

A.a.__get__(A(), A) # same as above

>>> A.a.__get__(A(), A)

>

>>> A().a

>

This bound function is always another because it has another object in __self__

>>> a = A()

>>> assert a.a.__self__ is a

__self__ will be passed as first argument self to the function A.a

EDIT: This is what it looks like:

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

Here the id repeats like 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

EDIT: For linux or what is not my machine and whatsoever I do not know

id(A().a)

will always give the same result except if you store this to a variable.

I do not know why but I would think that it is because of performance optimization.

For objects on the stack you do not need to allocate new space for an object every time you call a function.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值