Python內建函數(65)——type

來源:互聯網
上載者:User

標籤:string   index   return   intern   sse   orm   reference   style   定義類   

英文文檔:

class type(object)

class type(name, bases, dict)

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the __dict__ attribute. 

 

說明:

  1. 函數只傳入一個參數時,返回參數對象的類型。 傳回值是一個類型對象,通常與對象.__ class__返回的對象相同。

#定義類型A>>> class A:    name = ‘defined in A‘#建立類型A執行個體a>>> a = A()#a.__class__屬性>>> a.__class__<class ‘__main__.A‘>#type(a)返回a的類型>>> type(a)<class ‘__main__.A‘>#測試類型>>> type(a) == ATrue

  2. 雖然可以通過type函數來檢測一個對象是否是某個類型的執行個體,但是更推薦使用isinstance函數,因為isinstance函數考慮了父類子類間繼承關係。

#定義類型B,繼承A>>> class B(A):    age = 2#建立類型B的執行個體b>>> b = B()#使用type函數測試b是否是類型A,返回False>>> type(b) == AFalse#使用isinstance函數測試b是否類型A,返回True>>> isinstance(b,A)True

  3. 函數另一種使用方式是傳入3個參數,函數將使用3個參數來建立一個新的類型。其中第一個參數name將用作新的類型的類名稱,即類型的__name__屬性;第二個參數是一個元群組類型,其元素的類型均為類類型,將用作新建立類型的基類,即類型的__bases__屬性;第三個參數dict是一個字典,包含了新建立類的主體定義,即其值將複製到類型的__dict__屬性中。

#定義類型A,含有屬性InfoA>>> class A(object):    InfoA = ‘some thing defined in A‘#定義類型B,含有屬性InfoB>>> class B(object):    InfoB = ‘some thing defined in B‘#定義類型C,含有屬性InfoC>>> class C(A,B):    InfoC = ‘some thing defined in C‘#使用type函數建立類型D,含有屬性InfoD>>> D = type(‘D‘,(A,B),dict(InfoD=‘some thing defined in D‘))#C、D的類型>>> C<class ‘__main__.C‘>>>> D<class ‘__main__.D‘>#分別建立類型C、類型D的執行個體>>> c = C()>>> d = D()#分別輸出執行個體c、執行個體b的屬性>>> (c.InfoA,c.InfoB,c.InfoC)(‘some thing defined in A‘, ‘some thing defined in B‘, ‘some thing defined in C‘)>>> (d.InfoA,d.InfoB,d.InfoD)(‘some thing defined in A‘, ‘some thing defined in B‘, ‘some thing defined in D‘)

 

Python內建函數(65)——type

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.