一、 isinstance(obj,cls)
1. isinstance()与type()
-
检查一个对象(obj)是否是类(cls)实例化出来的
class Foo1: def __init__(self): self.name="大宝" class Foo2: def __init__(self): self.name="韦小宝" f1=Foo1() f2=Foo2() print(isinstance(f1,Foo1)) # True print(isinstance(f2,Foo1)) # False
-
type( ) 判断传入对象的类型
print(type([1,2.3]) == list) # True print(type(33) is int) # True print(type(3.5) in (int,float)) # True
2.不同之处
-
isinstance 它可以判断带有继承关系的类的对象
-
而 type 只能判断所属类的对象
class Foo1: def __init__(self): self.name = "大宝" class Foo2: def __init__(self): self.name = "韦小宝" f1 = Foo1() f2 = Foo2() print(isinstance(f2, Foo1)) # False print(isinstance(f2, Foo2)) # True print(type(f2) is Foo2) # True print(type(f2) is Foo1) # False
3.注意
-
不能说哪一种方法更好, 只能说哪一个更合适(因为没有最好的,只有最合适的)
二、issubclass(sub,super)
-
检查sub类是否是super类的派生类(孙子类, 重孙子类…)
#多继承 class Foo1: def __init__(self): self.name = "韦小宝" class Bar1: def run(self): print("快跑") class Bar2(Bar1,Foo1): def run(self): print("快跑") class Bar3: def speak(self): print("快说") print(issubclass(Bar2,Foo1)) # True print(issubclass(Bar2,Bar1)) # True print(issubclass(Bar3,Bar1)) # False # 多层继承 (父类--->父类) class Foo1: def __init__(self): self.name = "韦小宝" class Bar1(Foo1): def run(self): print("快跑") class Bar2(Bar1): def run(self): print("快跑") class Bar3(Bar2): def speak(self): print("快说") print(issubclass(Bar3,Foo1)) # True print(issubclass(Bar3,Bar1)) # True print(issubclass(Bar3,Bar2)) # True