2013-04-09 208 views
5

我該如何檢查一個類型是否是Python中的一個類型的子類型?我不是指一個類型的實例,而是比較類型實例本身。例如:如何檢查類型是否是Python中的某個類型的子類型?

class A(object): 
    ... 

class B(A): 
    ... 

class C(object) 
    ... 

# Check that instance is a subclass instance: 
isinstance(A(), A) --> True 
isinstance(B(), A) --> True 
isinstance(C(), A) --> False 

# What about comparing the types directly? 
SOME_FUNCTION(A, A) --> True 
SOME_FUNCTION(B, A) --> True 
SOME_FUNCTION(C, A) --> False 

回答

16

也許issubclass

>>> class A(object): pass 
>>> class B(A): pass 
>>> class C(object): pass 
>>> issubclass(A, A) 
True 
>>> issubclass(B, A) 
True 
>>> issubclass(C, A) 
False 
相關問題