Q28: What is a Metaclass and how does 'type' instantiate classes?

A Metaclass is the 'class of a class'. Just as objects are instances of classes, classes are instances of metaclasses. The default metaclass in Python is type. Metaclasses intercept class construction to inspect, modify, or validate class attributes during import time.

Creating Custom Metaclass
class UpperAttributeMeta(type):
    def __new__(cls, name, bases, dct):
        # Convert all attribute names to uppercase at class creation time
        uppercase_dct = {k.upper(): v for k, v in dct.items() if not k.startswith('__')}
        return super().__new__(cls, name, bases, uppercase_dct)

class CustomClass(metaclass=UpperAttributeMeta):
    feature = "data"
💡 Metaclass intercepts class creation to modify class attribute dictionaries dynamically.
Key Takeaways
  • type is the default metaclass for all Python classes.
  • Metaclasses customize class creation (__new__ / __init__ on type).
Knowledge Check

What is the return value of type(int) and type(type) in Python?