python是先運(yùn)行metaclass還是先有類屬性解析
答案
先有 “類屬性”,再有 “運(yùn)行 metaclass”
# 定義一個(gè)元類 class CustomMetaclass(type): def __new__(cls, name, bases, attrs): print('> cls', cls) print('> name', name) print('> attrs', attrs) print('> cls dict', cls.__dict__) # 在創(chuàng)建類時(shí)修改屬性 new_attrs = {} for attr_name, attr_value in attrs.items(): if isinstance(attr_value, str): new_attrs[attr_name] = attr_value.upper() else: new_attrs[attr_name] = attr_value obj = super().__new__(cls, name, bases, new_attrs) print(obj.__dict__) print(type(obj)) return obj # 使用元類創(chuàng)建類 class MyClass(metaclass=CustomMetaclass): name = 'John' age = 30 greeting = 'Hello' def say_hello(self): print(self.greeting) # 創(chuàng)建類的實(shí)例并調(diào)用方法 obj = MyClass() print(obj.name) # 輸出: 'JOHN' print(obj.age) # 輸出: 30 obj.say_hello() # 輸出: 'Hello'
輸出結(jié)果
> cls <class '__main__.CustomMetaclass'>
> name MyClass
> attrs {'__module__': '__main__', '__qualname__': 'MyClass', 'name': 'John', 'age': 30, 'greeting': 'Hello', 'say_hello': <function MyClass.say_hello at 0x1025c2200>}
> cls dict {'__module__': '__main__', '__new__': <staticmethod(<function CustomMetaclass.__new__ at 0x1025c2290>)>, '__doc__': None}
{'__module__': '__MAIN__', 'name': 'JOHN', 'age': 30, 'greeting': 'HELLO', 'say_hello': <function MyClass.say_hello at 0x1025c2200>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
<class '__main__.CustomMetaclass'>
JOHN
30
以上就是python是先運(yùn)行metaclass還是先有類屬性解析的詳細(xì)內(nèi)容,更多關(guān)于python metaclass類屬性的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python隨機(jī)函數(shù)random隨機(jī)獲取數(shù)字、字符串、列表等使用詳解
這篇文章主要介紹了Python隨機(jī)函數(shù)random使用詳解包含了Python隨機(jī)數(shù)字,Python隨機(jī)字符串,Python隨機(jī)列表等,需要的朋友可以參考下2021-04-04Python plt 利用subplot 實(shí)現(xiàn)在一張畫布同時(shí)畫多張圖
這篇文章主要介紹了Python plt 利用subplot 實(shí)現(xiàn)在一張畫布同時(shí)畫多張圖,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-02-02Python讀取Windows和Linux的CPU、GPU、硬盤等部件溫度的讀取方法
本文詳細(xì)介紹了如何使用Python在Windows和Linux系統(tǒng)上通過OpenHardwareMonitor和psutil庫(kù)讀取CPU、GPU等部件的溫度,包括Windows下的兩種方法以及Linux下的簡(jiǎn)單實(shí)現(xiàn),感興趣的小伙伴跟著小編一起來看看吧2025-02-02pandas讀取excel,txt,csv,pkl文件等命令的操作
這篇文章主要介紹了pandas讀取excel,txt,csv,pkl文件等命令的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03NumPy中np.random.rand函數(shù)的實(shí)現(xiàn)
np.random.rand是NumPy庫(kù)中的一個(gè)函數(shù),用于生成隨機(jī)數(shù),本文主要介紹了NumPy中np.random.rand函數(shù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07用Python做的數(shù)學(xué)四則運(yùn)算_算術(shù)口算練習(xí)程序(后添加減乘除)
這篇文章主要介紹了用Python做的數(shù)學(xué)四則運(yùn)算_算術(shù)口算練習(xí)程序(后添加減乘除),需要的朋友可以參考下2016-02-02