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)鍵字可以動(dòng)態(tài)的創(chuàng)建類,接收參數(shù)(類名,父類元組,屬性的字典),如創(chuàng)建一個(gè)類,沒有父類,沒有屬性,命令如下:
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)建帶實(shí)例方法的類,命令如下:
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)容,感謝大家對(duì)腳本之家的支持。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
