欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python使用type關(guān)鍵字創(chuàng)建類步驟詳解

 更新時間:2019年07月23日 15:59:49   作者:卡和我  
在本文里我們給讀者們整理了關(guān)于Python如何使用type關(guān)鍵字創(chuàng)建類的相關(guān)知識點,需要的朋友們參考學(xué)習(xí)下。

Python使用type關(guān)鍵字創(chuàng)建類

打開命令行窗口,輸入python,進(jìn)入python交互環(huán)境

python

一般創(chuàng)建類使用class關(guān)鍵字即可,測試命令如下:

class Coo:

  pass

obj1 = Coo()

print (obj1)

c = Coo

obj2 = c()

print (obj2)

type關(guān)鍵字可以動態(tài)的創(chuàng)建類,接收參數(shù)(類名,父類元組,屬性的字典),如創(chuàng)建一個類,沒有父類,沒有屬性,命令如下:

Test = type('Test',(),{})

print (Test)

t = Test()

print (t)

接收type函數(shù)返回的變量可以是任意命令,傳入type的才是類名,變量只是類的引用

使用type創(chuàng)建有屬性的類,命令如下:

Test = type('Test2',(),{'hi':True})

print (Test)

print (Test.hi)

t = Test()

print (t.hi)

使用type創(chuàng)建并繼承的類

Test3 = type('Test3',(Test,),{})

t = Test3()

print (t.hi)

使用type創(chuàng)建帶實例方法的類,命令如下:

def echo(self):

  print (self.hi)

Test4 = type('Test4',(Test,),{'echo':echo})

hasattr(Test,'echo')

hasattr(Test4,'echo')

使用type創(chuàng)建帶靜態(tài)方法,命令如下:

@staticmethod

def staticm():

  print ('staticm')

Test5 = type('Test5',(Test,),{'echo':echo,'staticm':staticm})

t = Test5()

t.staticm()

使用type創(chuàng)建帶類方法的類,命令如下:

@classmethod

def classm(cls):

  print (cls.hi)

Test6 = type('Test6',(Test,),{'echo':echo,'staticm':staticm,'classm':classm})

Test6.classm()

以上就是相關(guān)Python如何使用type關(guān)鍵字創(chuàng)建類的全部內(nèi)容,感謝大家對腳本之家的支持。

相關(guān)文章

最新評論