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

猜你喜欢

转载自blog.csdn.net/weixin_33939380/article/details/93401912