python中不可变对象,python中的不可变对象

I see a article about the immutable object.

It says when:

variable = immutable

As assign the immutable to a variable.

for example

a = b # b is a immutable

It says in this case a refers to a copy of b, not reference to b.

If b is mutable, the a wiil be a reference to b

so:

a = 10

b = a

a =20

print (b) #b still is 10

but in this case:

a = 10

b = 10

a is b # return True

print id(10)

print id(a)

print id(b) # id(a) == id(b) == id(10)

if a is the copy of 10, and b is also the copy of 10, why id(a) == id(b) == id(10)?

解决方案

While that article may be correct for some languages, it's wrong for Python.

When you do any normal assignment in Python:

some_name = some_name_or_object

You aren't making a copy of anything. You're just pointing the name at the object on the right side of the assignment.

Mutability is irrelevant.

More specifically, the reason:

a = 10

b = 10

a is b

is True, is that 10 is interned -- meaning Python keeps one 10 in memory, and anything that is set to 10 points to that same 10.

If you do

a = object()

b = object()

a is b

You'll get False, but

a = object()

b = a

a is b

will still be True.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值