7. is 和is not运算

Python中任何的对象(数字,字符串以及自己写的类创建的对象)都存在于计算机内存(注意是运行内存)中。内存你可以认为是村里的联排别墅,自东到西每一户都有一个整数的门牌号1,2,3,4....,内存也是如此,我们要把对象放在别墅中,每个别墅只能放一个对象。

内存地址

id() 函数

作用

返回对象的内存地址的标识值。该值是一个整数,在此对象的生命周期中保证是唯一且恒定的。

你可以认为是返回别墅的门牌号。

调用格式

id(object)

is 和 is not 运算

作用

id 相同就一定是同一个对象。

语法

x is y
或
x is not y

x, y 表示表达式或变量返回的数据对象

示例

# is / is not 运算示例

class Dog:
    def __init__(self, k, c):
        self.kind = k  # 种类
        self.color = c  # 颜色
        print(self.color, '的', self.kind, '小狗被创建')
    def eat(self, food):
        print(self.color, '的', self.kind, '吃', food)

dog1 = Dog('哈士奇', '灰色')
dog2 = Dog('藏獒', '棕色')
dog3 = dog1
print(dog1 is dog2)  # False
print(dog1 is dog3)  # True

None对象的判断

在计算机内存中,None对象只有一个且一直存在,因此判断一个变量是否绑定None,经常使用is / is not 运算而不使用 == 和 != 的值比较运算。

示例

if obj is None:
    print('obj变量绑定的是None对象')

视频讲解