Python 中的元類

2021-10-08 00:07:14 字數 1041 閱讀 6820

如果看完以後還是感覺莫名其妙,執行這樣乙個demo 可能會對你有所幫助:

(元類程式設計在我看來,如果你想開發一些框架,可以嘗試一下)

class upperattrmetaclass(type):

_type = dict()

def __new__(cls, cls_name, bases, attr_dict):

news_cls = type.__new__(cls, cls_name, bases, attr_dict)

print('cls_name', cls_name)

print('bases', bases)

print('news_cls:', news_cls)

for name, val in attr_dict.items():

print('_name:', name, "_val:", val)

upperattrmetaclass._type[attr_dict['name']] = news_cls

return news_cls

class spider(object, metaclass=upperattrmetaclass):

name = 'bar'

def hello(self):

print('hello, word')

def find_one(self):

print('find_one')

class baijiaho(spider):

name = 'baijiahao'

def get_list(self):

print([1, 2, 3, 4, 5])

class toutiao(spider):

name = 'toutiao'

def get_list(self):

print([4, 5])

print(spider._type)

b = spider._type.get('baijiahao')()

b.get_list()

python中的元類

python中的元類大家都可能比較很陌生,因為大家都聽說過99 的情況下是用不到元類的,但是大家對類確很了解,大家都知道在python中萬物皆物件,那麼python中的類是不是物件呢?物件的樣子 1,物件可以在程式中動態的進行建立,python的語言動態特性。2,物件可以通過 class 獲取該物件...

python中的元類

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

Python中的元類 metaclass

在wiki上面,metaclass是這樣定義的 in object oriented programming,a metaclass is a class whose instances are classes.python中物件模型如下圖 其中,實線表示 is kind of 派生 的關係,虛線表...