一. 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
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(Foo1):
name = "海绵宝宝"
f1 = Foo1()
f2 = Foo2()
print(isinstance(f2,Foo2)) # True
print(isinstance(f2,Foo1)) # 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