python是先運行metaclass還是先有類屬性解析
答案
先有 “類屬性”,再有 “運行 metaclass”
# 定義一個元類 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)建類時修改屬性 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)建類的實例并調(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是先運行metaclass還是先有類屬性解析的詳細內(nèi)容,更多關(guān)于python metaclass類屬性的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python隨機函數(shù)random隨機獲取數(shù)字、字符串、列表等使用詳解
這篇文章主要介紹了Python隨機函數(shù)random使用詳解包含了Python隨機數(shù)字,Python隨機字符串,Python隨機列表等,需要的朋友可以參考下2021-04-04Python plt 利用subplot 實現(xiàn)在一張畫布同時畫多張圖
這篇文章主要介紹了Python plt 利用subplot 實現(xiàn)在一張畫布同時畫多張圖,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02Python讀取Windows和Linux的CPU、GPU、硬盤等部件溫度的讀取方法
本文詳細介紹了如何使用Python在Windows和Linux系統(tǒng)上通過OpenHardwareMonitor和psutil庫讀取CPU、GPU等部件的溫度,包括Windows下的兩種方法以及Linux下的簡單實現(xiàn),感興趣的小伙伴跟著小編一起來看看吧2025-02-02pandas讀取excel,txt,csv,pkl文件等命令的操作
這篇文章主要介紹了pandas讀取excel,txt,csv,pkl文件等命令的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03NumPy中np.random.rand函數(shù)的實現(xiàn)
np.random.rand是NumPy庫中的一個函數(shù),用于生成隨機數(shù),本文主要介紹了NumPy中np.random.rand函數(shù)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07用Python做的數(shù)學(xué)四則運算_算術(shù)口算練習(xí)程序(后添加減乘除)
這篇文章主要介紹了用Python做的數(shù)學(xué)四則運算_算術(shù)口算練習(xí)程序(后添加減乘除),需要的朋友可以參考下2016-02-02