Back
+15 XP
Concept

Metaclasses: Creating Classes from Classes

A metaclass is the class of a class. Subclassing `type` lets you customize class creation, enforce naming conventions, or inject methods before classes are built 🧙.

python
class UpperAttrMeta(type):
    def __new__(mcs, name, bases, attrs):
        # Uppercase all custom attributes:
        new_attrs = {}
        for k, v in attrs.items():
            new_attrs[k.upper() if not k.startswith("__") else k] = v
        return super().__new__(mcs, name, bases, new_attrs)

class Demo(metaclass=UpperAttrMeta):
    greeting = "hello"

print(hasattr(Demo, "GREETING"))  # True 🧙
print(Demo.GREETING)              # 'hello'

# 67. Metaclasses: Creating Classes from Classes A metaclass is the class of a class. Subclassing `type` lets you customize class creation, enforce naming conventions, or inject methods before classes are built 🧙. ```python class UpperAttrMeta(type): def __new__(mcs, name, bases, attrs): # Uppercase all custom attributes: new_attrs = {} for k, v in attrs.items(): new_attrs[k.upper() if not k.startswith("__") else k] = v return super().__new__(mcs, name, bases, new_attrs) class Demo(metaclass=UpperAttrMeta): greeting = "hello" print(hasattr(Demo, "GREETING")) # True 🧙 print(Demo.GREETING) # 'hello' ``` Remember Tim Peters' famous rule: 'Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't.' 🧙 --- ### Question What base class must a custom metaclass inherit from in Python? 🧠 - [ ] a. `type` 🧙 - [ ] b. `object` - [ ] c. `abc.ABC` - [ ] d. `classmethod` --- ### Challenge Write metaclass `StrictMeta(type)` that injects attribute `__verified__ = True` into every class created with it. Create `class Shield(metaclass=StrictMeta): pass`. Print `Shield.__verified__`. 🎯 <details> <summary>Solution</summary> ```python class StrictMeta(type): def __new__(mcs, name, bases, attrs): attrs["__verified__"] = True return super().__new__(mcs, name, bases, attrs) class Shield(metaclass=StrictMeta): pass print(Shield.__verified__) ``` </details>

Checkpoint

What base class must a custom metaclass inherit from in Python? 🧠

Practice

Write metaclass `StrictMeta(type)` that injects attribute `__verified__ = True` into every class created with it. Create `class Shield(metaclass=StrictMeta): pass`. Print `Shield.__verified__`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks