metaclass 拦截类的创建,并返回

def upper_attr(future_class_name, future_class_parents, future_class_attr):
    #遍历属性字典,把不是__开头的属性名字变为大写
    newAttr = {}
    for name,value in future_class_attr.items():#遍历字典
        if not name.startswith("__"):#如果不是以__开头
            newAttr[name.upper()] = value
    #         将future_class_attr字典中的键大写,然后赋值
    return type(future_class_name, future_class_parents, newAttr)#第三个参数为新修改好的值(类名,父类,字典)
class Foo(object, metaclass=upper_attr):
    # 使用upper_attr对类中值进行修改
    bar = 'bip'#一开始创建Foo类时
print(hasattr(Foo, 'bar'))# hasattr查看Foo类中是否存在bar属性
print(hasattr(Foo, 'BAR'))
f = Foo()#实例化对象
print(f.BAR)#输出

2020-05-08

原文地址:https://www.cnblogs.com/hany-postq473111315/p/12846911.html