Metaclass

文章目录

实现一个将类的属性全部转为大写的metaclass

What are metaclasses in Python?

  • 实现一个将类的属性全部转为大写的metaclass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class UpperAttrMetaclass(type):
def __new__(cls, clsname, bases, attrs):
uppercase_attrs = {
attr if attr.startswith('__') else attr.upper(): v
for attr, v in attrs.items()
}
# return type(clsname, bases, uppercase_attrs)
# return type.__new__(cls, clsname, bases, uppercase_attrs)
return super(UpperAttrMetaclass, cls).__new__(
cls, clsname, bases, upptercase_attrs)

# 使用
class Item(metaclass=UpperAttrMetaclass):
pass
  • __new__在实例类创建的时候调用