Python基础02 变量

Python中的变量有两个特点:

1. 无需声明

a = 1

2. 不与类型绑定

a = 1
a = 'hello world'

变量名只是内存中具体对象的一个引用(reference)。

 

对于 a = 1,内存模型如下:

对于

a = 1
b = a

内存模型如下:

 

可以通过id(x)获取变量x所引用对象的内存地址

a = 1
b = a
print('address of the object referenced by a:', id(a))
print('address of the object referenced by b:', id(a))

输出如下:

address of the object referenced by a: 4415551552
address of the object referenced by b: 4415551552

 

对于Python中的list,list的每个元素都是一个引用。

mylist = [1, 2, 3]
print('address of the object referenced by mylist:', id(mylist))
for index, item in enumerate(mylist):
    print('address of the object referenced by mylist[{}]: {}'.format(index, id(item)))

输出:

address of the object referenced by mylist: 4350869128
address of the object referenced by mylist[0]: 4345657408
address of the object referenced by mylist[1]: 4345657440
address of the object referenced by mylist[2]: 4345657472

内存模型如下:

 

对于Python中函数的参数,也只是对传递进来的变量所引用对象的一个引用。

 

转载于:https://www.cnblogs.com/gattaca/p/7571563.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值