Python还有一些其他运算符,“测试”运算符,两个“测试”运算符是同一性测试运算符和成员测试运算符,所谓“测试”就是判断之意,因此它们的运算结果是布尔值,它们也属于关系运算符。
6.6.1 同一性测试运算符
同一性测试运算符就是测试两个对象是否同一个对象,类似于“ ==
”运算符,不同之处是,“ ==
”测试两个对象的内容是否相同,当然如果是同一对象“ ==
”也返回 True 。
同一性测试运算符有两个: is
和 is not
,is
是判断是同一对象,is not
是判断不是同一对象。
例如:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Tony", 18)
p2 = Person("Tony", 18)
print(p1 == p2)
print(p1 is p2)
print(p1 != p2)
print(p1 is not p2)
执行结果:
False
False
True
True
上述代码自定义类 Person
,它有两个实例变量 name
和 age
,然后创建了两个 Person
对象 p1
和 p2
,它们具有相同的 name
和 age 实例变量 。
那么是否可以说 p1 与 p2 是同一个对象 (p1 is p2 为 True) ?
程序运行结果不是,因为这里实例化了两个 Person 对象(Person ("Tony ",18)
语句是创建对象)。
因为 ==
虽然是比较两个对象的内容是否相当,但是也需要告诉对象比较的规则是什么,是比较 name
还是 age
?这需要在定义类时重写 eq
方法,指定比较规则。
对代码进行修改:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
if self.name == other.name and self.age == other.age:
return True
else:
return False
p1 = Person("Tony", 18)
p2 = Person("Tony", 18)
print(p1 == p2)
print(p1 is p2)
print(p1 != p2)
print(p1 is not p2)
执行结果:
True
False
False
True
上述代码重写 eq
方法,其中定义了只有在 name
和 age
都同时相等时,两个Person
对象p1
和p2
才相等,即 p1 == p2
为 True
。
注意,p1 is p2
还是为 False
的。
6.6.2 成员测试运算符
成员测试运算符可以测试在一个序列( sequence)
对象中是否包含某一个元素。
成员测试运算符有两个 : in
和 not in
。
in
是测试是否包含某一个元素;not in
是测试是否不包含某一个元素。
例如:
string_a = "Hello"
print("e" in string_a)
print("ell" not in string_a)
list_a = [1, 2]
print(2 in list_a)
print(1 not in list_a)
执行结果:
True
False
True
False