" />

欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python是先運行metaclass還是先有類屬性解析

 更新時間:2023年05月31日 09:46:34   作者:ponponon  
這篇文章主要為大家介紹了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)文章

最新評論