python 中,是先运行 metaclass 还是先有类属性?

发布于:2023-05-29 ⋅ 阅读:(236) ⋅ 点赞:(0)

答案:先有 “类属性”,再有 “运行 metaclass”

# 定义一个元类
class CustomMetaclass(type):
    def __new__(cls, name, bases, attrs):
        print('> cls', cls)
        print('> name', name)
        print('> attrs', attrs)
        print('> cls dict', cls.__dict__)
        # 在创建类时修改属性
        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

# 使用元类创建类


class MyClass(metaclass=CustomMetaclass):
    name = 'John'
    age = 30
    greeting = 'Hello'

    def say_hello(self):
        print(self.greeting)


# 创建类的实例并调用方法
obj = MyClass()
print(obj.name)         # 输出: 'JOHN'
print(obj.age)          # 输出: 30
obj.say_hello()         # 输出: 'Hello'

网站公告

今日签到

点亮在社区的每一天
去签到