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'輸出結果
> 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)容,更多關于python metaclass類屬性的資料請關注腳本之家其它相關文章!
相關文章
Python+matplotlib實現(xiàn)計算兩個信號的交叉譜密度實例
這篇文章主要介紹了Python+matplotlib實現(xiàn)計算兩個信號的交叉譜密度實例,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
Python使用cx_Oracle庫連接Oracle數(shù)據(jù)庫指南
這篇文章主要為大家介紹了Python使用cx_Oracle庫連接Oracle數(shù)據(jù)庫指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12
Celery+django+redis異步執(zhí)行任務的實現(xiàn)示例
本文主要介紹了Celery+django+redis異步執(zhí)行任務的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-04-04

