我的奶牛
10.48M · 2026-03-26
metaclass其实就是最常用的元类,也就是:创建类的类
元类一般用来:
假设要实现一个功能:让某个类中定义的所有属性名自动变成大写
# 方式一:直接改字典
class UpperMeta(type):
"""把除 __xxx__ 以外的所有属性名强制变成大写"""
def __new__(mcs, name, bases, namespace, **kw):
new_ns = {}
for k, v in namespace.items():
if k.startswith('__') and k.endswith('__'):
new_ns[k] = v # 魔法方法保持原样
else:
new_ns[k.upper()] = v # 其余统一变大写
return super().__new__(mcs, name, bases, new_ns, **kw)
class Foo(metaclass=UpperMeta):
x = 1
y = 2
def hello(self):
return 'hello'
print(Foo.X) # 1
print(Foo.Y) # 2
print(Foo.HELLO()) # 'hello'
但是在,一般场景下,可以使用类装饰器来代替,因为它更加简单,可以避开元类的复杂性。 juejin.cn/post/752209…