Writing Custom Metaclasses
Use __new__ and __init__ in metaclasses to customize class creation.
Declaring a Metaclass
Pass metaclass=MyMeta in the class definition to use a custom metaclass. The metaclass must inherit from type.
class MyMeta(type):
pass
class Foo(metaclass=MyMeta):
pass
print(type(Foo)) # <class '__main__.MyMeta'>Overriding __new__
__new__(mcs, name, bases, namespace) creates the class object. Use it to modify the namespace before the class is built.
class UpperAttrMeta(type):
def __new__(mcs, name, bases, namespace):
upper = {k.upper(): v for k, v in namespace.items()
if not k.startswith("_")}
return super().__new__(mcs, name, bases, {**namespace, **upper})
class Config(metaclass=UpperAttrMeta):
debug = True
print(Config.DEBUG) # TrueAll lessons in this course
- How Python Classes Are Created
- Writing Custom Metaclasses
- Descriptors: __get__, __set__, __delete__
- __slots__ and Memory Optimization