对象相关的内置函数
Python中有几个内置函数与对象相关,分别是身份运算符、isinstance和issubclass。
身份运算符
身份运算符用于比较两个对象的内存地址,以判断它们是否是同一个对象。
class Person(object): def __init__(self, name, age): self.name = name self.age = age p1 = Person('张三', 18) p2 = Person('张三', 18) p3 = p1 print(p1 is p2) # False print(p1 is p3) # True
isinstance
isinstance是一个内置函数,用于判断一个实例对象是否由某个类(或其子类)实例化创建。
class Person(object): def __init__(self, name, age): self.name = name self.age = age class Student(Person): def __init__(self, name, age, score): super().__init__(name, age) self.score = score class Dog(object): def __init__(self, name, color): self.name = name self.color = color p = Person('tony', 18) s = Student('jack', 20, 90) d = Dog('旺财', '白色') print(isinstance(p, Person)) # True,对象p由Person类创建 print(isinstance(s, Person)) # True,对象s由Person类的子类创建 print(isinstance(d, Person)) # False,对象d与Person类没有关系
issubclass
issubclass用于判断两个类之间的继承关系。
class Person(object): def __init__(self, name, age): self.name = name self.age = age class Student(Person): def __init__(self, name, age, score): super().__init__(name, age) self.score = score class Dog(object): def __init__(self, name, color): self.name = name self.color = color print(issubclass(Student, Person)) # True print(issubclass(Dog, Person)) # False