python的 type 函數有兩個用法,當只有一個參數的時候,返回對象的類型。當有三個參數的時候返回一個類對象。python
一個參數:type(object)函數
三個參數:type(name,bases,dict)ui
一個參數時,type()返回一個對象的數據類型this
1 >>> type(1) 2 <class 'int'> 3 >>> type('alex') 4 <class 'str'> 5 >>> type([1,2,3]) 6 <class 'list'> 7 >>> type((1,2,3)) 8 <class 'tuple'> 9 >>> type({'zero':0,'one':1}) 10 <class 'dict'> 11 >>> type(1) == int 12 True 13 >>>
三個參數時:spa
name:類名code
bases: 父類的元組對象
dict: 類的屬性方法和值組成的鍵值對blog
建立一個類繼承
1 # 構造函數 2 def __init__(self, name): 3 self.name = name 4 # 實例(普通)方法 5 def instancetest(self): 6 print('this is instance method') 7 8 # 類方法 9 @classmethod 10 def classtest(cls): 11 print('This is a class method') 12 13 # 靜態方法 14 @staticmethod 15 def statictest(n): 16 print('This is a static method %s' % n) 17 18 #建立類 19 test_property = {'number': 1, '__init__':__init__,'instancetest1':instancetest, 20 'classtest': classtest, 'statictest': statictest}# 屬性和方法 21 Test = type('Tom', (object,), test_property) 22 23 # 實例化 24 test = Test('alex') 25 print(test.name) 26 print(test.number) 27 test.instancetest1() 28 test.classtest() 29 test.statictest(7)
執行結果:ip
1 alex 2 1 3 this is instance method 4 This is a class method 5 This is a static method 7
用help()打印Test的詳細信息
class Tom(builtins.object) | Tom(name) | | Methods defined here: | | __init__(self, name) | # 構造函數 | | instancetest1 = instancetest(self) | # 實例(普通)方法 | | ---------------------------------------------------------------------- | Class methods defined here: | | classtest() from builtins.type | # 類方法 | | ---------------------------------------------------------------------- | Static methods defined here: | | statictest(n) | # 靜態方法 | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | number = 1
能夠看出咱們建立了一個Test類,包含一個實例方法包含一個構造方法__init__,實例方法statictest,類方法classtest,靜態方法statictest1,和一個屬性number =1。
注意:
type爲對象的頂點,全部對象都建立自type。
object爲類繼承的頂點,全部類都繼承自object。
python中萬物皆對象,一個python對象可能擁有兩個屬性,__class__
和 __base__
,__class__
表示這個對象是誰建立的,__base__
表示一個類的父類是誰。
1 >>> object.__class__ 2 <class 'type'> 3 >>> type.__base__ 4 <class 'object'>
能夠得出結論:
判斷一個對象時否來自一個已知類型
isinstance(object, classinfo)
若是對象的類型與參數二的類型(classinfo)相同則返回 True,不然返回 False。
1 >>>a = 2 2 >>> isinstance (a,int) 3 True 4 >>> isinstance (a,str) 5 False 6 >>> isinstance (a,(str,int,list)) # 是元組中的一個返回 True 7 True
isinstance() 與 type() 區別:
type() 不會認爲子類是一種父類類型,不考慮繼承關係。
isinstance() 會認爲子類是一種父類類型,考慮繼承關係。
若是要判斷兩個類型是否相同推薦使用 isinstance()。
1 class A(object): 2 pass 3 class B(A): 4 pass 5 6 print(isinstance(A(), A)) 7 print(isinstance(B(), A)) 8 print(type(A()) == A) 9 print(type(B()) == A)
執行結果:
1 True 2 True 3 True 4 False