Python中变量的属性以及判断方法

1.变量的属性  

  在Python中,创建一个变量会给这个变量分配三种属性:

    id ,代表该变量在内存中的地址;

    type,代表该变量的类型;

    value,该变量的值;

1 x = 10
2 print(id(x))
3 print(type(x))
4 print(x)
5 
6 ---
7 1689518832
8 <class 'int'>
9 10

 2.变量的比较

  - 身份的比较

    is 关键字用来判断变量的身份,即 id;

  - 值的比较

    == 用来判断变量的值是否相等,即value;

 1 C:UsersAdministrator>python
 2 Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AM
 3 D64)] on win32
 4 Type "help", "copyright", "credits" or "license" for more information.
 5 >>>
 6 >>> x=10
 7 >>> y=10
 8 >>>
 9 >>> id(x)
10 1711080176
11 >>> id(y)
12 1711080176
13 >>>
14 >>> x is y
15 True
16 >>>
17 >>> x == y
18 True
19 >>>
20 >>> x=300
21 >>> y=300
22 >>>
23 >>> id(x)
24 5525392
25 >>> id(y)
26 11496656
27 >>>
28 >>> x is y
29 False
30 >>> x == y
31 True
32 >>>

  - 总结

    - is 同,则value一定相等;

    - value同,则is不一定相等;

作者:Standby一生热爱名山大川、草原沙漠,还有妹子
出处:http://www.cnblogs.com/standby/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/standby/p/6986754.html