python 動態建立乙個類

2021-08-07 19:42:30 字數 1898 閱讀 2774

class animal:

def eat(self)

print("------------eat----------")

class dog(animal)

pass 

wangcai = dog() 

wangcai.eat()

輸出:--------eat------ 

cat = type("cat",(animal,),{}) 

xiaohuamao = cat()

xiaohuamao.eat()

輸出:---------eat----------

元類就是用來建立類的,你建立類就是為了建立類的例項物件,不是嗎?但是我們已經學習到了python中的類也是物件 

元類就是用來建立這些類(物件)的,元類就是類的類)

cat.__class__

輸出: type 

wangcai.__class__

輸出:__main__.dog 

xiaohuamao.__class__

輸出:__main__.cat (本檔案的cat類建立xiaohuamao物件)

cat.__class__

輸出: type (type建立的cat類)

dog.__class__

輸出:type

一般情況下,我們幾乎不用type建立類

但可由此引申__metaclass__ 屬性,以下為例子:

python2 

#coding=utf-8 

def upper_attr (future_class_name, future_class_parents, future_class_attr): 

#遍歷屬性字典,把不是__開頭的屬性名字變為大寫 

newattr = {} (定義乙個空字典)

for name,value in future_class_attr.items(): 

if not name.startswith("__"):

newattr[name.upper()] = value 

#呼叫type來建立乙個類 

return type(future_class_name, future_class_parents,newattr)

class foo(object):

__metaclass__ = upper_attr  #設定foo類的元類為upper_attr 

bar = 'bip' 

print (hasattr(foo, ' bar '))  

print (hasattr(foo, ' bar')) 

輸出:false 

true     (說明只有大寫的bar而沒有小寫的bar)

python3

#coding = utf-8 

def upper_attr(future_class_name,future_class_parents, future_class_attr):

#遍歷屬性字典,把不是__開頭的屬性名字變為大寫 

newattr = {}

for name,value in future_class_attr.items():

if not name.startswith("__"):

newattr[name.upper()] = value 

#呼叫type來建立乙個類 

return type(future_class_name, future_class_parents, newattr)

class foo(object, metaclass = upper_attr):

bar = 'bip' 

print(hasattr(foo, ' bar'))

print(hasattr(foo, 'bar'))

python 用type動態建立乙個類

class person object def init self,name,age self.name name self.age age p person alex 22 上述 中,p 是通過 person 類例項化的物件,其實,不僅 p 是乙個物件,person類本身也是乙個物件,因為在pyt...

python建立乙個元類

其他我們建立乙個類目的是為了建立該類的例項物件,而元類就是用來建立類的。換個理解方式就是,元類就是建立類的類。在python中可以使用type函式建立乙個類,參考 python中type的用法 用法如下 tpye name,bases,dict 實際上type 函式就是乙個元類,是python預設用...

通過元類建立乙個Python類

最開始學python的時候我們定義類都是 class classname pass當熟悉了元類的概念之後我們可以這樣建立 classname type classname 當有父類的時候 class classname object pass等價於 classname type classname ...