Python的一些細節 II
阿新 • • 發佈:2019-09-15
1. isinstance() 與 type() 區別
class type(name, bases, dict)
- name -- 類的名稱。
- bases -- 基類的元組。
- dict -- 字典,類內定義的名稱空間變數。
- 返回值:一個引數,返回物件的型別;三個引數,返回新的型別物件。
>>> class A(object): pass a = A() print(type(a)) print(type(A)) >>> <class '__main__.A'> <class 'type'>
不難發現,定義的A類本身的型別是 type,當程式使用 class 定義 A類時,也可理解為定義了一個特殊的物件(type 類的物件),並將該物件賦值給 A變數。因此,程式使用 class 定義的所有類都是 type 類的例項。
實際上 Python 完全允許使用 type() 函式(相當於 type 類的構造器函式)來建立 type 物件,又由於 type 類的例項就是類,因此 Python 可以使用 type() 函式來動態建立類。
## >>> class Test(object): def test(self): self.classname = 'test' print("i am base class") def hello(self): # 必須要加self self.name = 10 print("hello") T = type("HELLO", (Test,), {"a": 1, "h":hello}) t = T() print(T) print(type(t)) print(t.a) t.h() t.test() print(t.classname) print(t.name) ## <<< <class '__main__.HELLO'> <class '__main__.HELLO'> 1 hello i am base class test 10
isinstance() 函式來判斷一個物件是否是一個已知的型別,類似 type()(單個屬性)。
isinstance (object, classinfo)
- object -- 例項物件。
- classinfo -- 可以是直接或間接類名、基本型別或者由它們組成的元組。
>>>
print(isinstance(12,str))
print(isinstance([1, 2, 3], (str, int, list)))
<<<
False
True
type(object) 和 isinstance( ) 比較:
class A:
pass
class B(A):
pass
print(isinstance(A(), A)) # returns True
print(type(A()) == A) # returns True
print(isinstance(B(), A)) # returns True
print(type(B()) == A) # returns False
建立一個A物件,再建立一個繼承A物件的B物件
使用 isinstance( ) 和 type( ) 來比較 A( ) 和 A 時,由於它們的型別都是一樣的,所以都返回了 True。
而B物件繼承於A物件,在使用isinstance()函式來比較 B( ) 和 A 時,由於考慮了繼承關係,所以返回了 True,使用 type( ) 函式來比較 B( ) 和 A 時,不會考慮 B( )繼承,所以返回