Python使用type關鍵字建立類步驟詳解

2022-09-27 09:30:14 字數 1198 閱讀 8955

python使用type關鍵字建立類

開啟命令列視窗,輸入python,進入python互動環境

python

一般建立類使用class關鍵字即可,測試命令如下:

class coo:

pass

obj1 = coo()

print (obj1)

c = coo

obj2 = c()

print (obj2)

type關鍵字可以動態的建立類,接收引數(類名,父類元組,屬性的字典),如建立乙個類,沒有父類,沒有屬性,命令如下:

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

print (test)

t = test()

print (t)

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

使用type建立有屬性的類,命令如下:

test = type('test2',(),)

print (test)

print (test.hi)

t = test()

print (t.hi)

使用type建立並繼承的類

test3 = type('test3',(test,程式設計客棧),{})

t = test3()

print (t.hi)

使用type建立帶例項方法的類,命令如下:

def echo(self):

print (self.hi)

test4 = type('test4',(test,),)

hasattr(test,'echo')

hasattr(test4,'echo')

使用type創www.cppcns.com程式設計客棧建帶靜態方法,命令如下:

@staticmethod

def staticm():

print ('staticm')

test5 = type('test5',(test,),)

t = teswvvosst5()

t.staticm()

使用type建立帶類方法的類,命令如下:

@classmethod

def classm(cls):

print (cls.hi)

test6 = type('test6',(test,),)

test6.classm()

Goland中Type關鍵字的幾種使用場景

type 關鍵字可以用來定義結構體 type user struct其實就是給原來的型別加乙個別名,方便我們後面呼叫。type str string 在下面的 中str就可以代替string使用了 var str1 str 我是乙個型別別名 這裡不只是基礎型別 結構體 復合型別 也可以使用別名 ty...

this關鍵字使用

一,表示類中屬性 1,沒有使用this的情況 class person public string getinfo public class thisdemo01 執行結果 姓名 null,年齡 0 可以得出結論 此時並沒有正確將內容賦給屬性 假設身邊有乙隻筆,遠處也有乙隻筆,肯定會就近拿身邊的筆。...

new關鍵字 this關鍵字 base關鍵字

使用new,所做的三件事 1.類是引用物件,引用物件是在堆中開闢空間 在堆中開闢空間 2.在開闢的堆空間中建立物件 3.呼叫物件的構建函式 4.隱藏父類成員 子類的成員可以與隱藏從父類繼承的成員,類似於重寫。public new void sayhello this關鍵字的使用 1.代表當前類的物件...