Sobes.tech
Junior — Middle

What does a metaclass object consist of and how is it used in Python?

sobes.tech AI

Answer from AI

In Python, a metaclass is a class that creates other classes. Put simply, a class is an object, and a metaclass is a "class for classes".

A metaclass object consists of:

  • the name of the class,
  • base classes,
  • a dictionary of class attributes.

By default, the metaclass in Python is type. When you create a class, Python calls the metaclass to create that class.

Using metaclasses allows you to control the class creation process, for example, automatically add methods, check attributes, or modify class behavior.

An example of a simple metaclass:

class Meta(type):
    def __new__(cls, name, bases, dct):
        print(f"Creating class {name}")
        return super().__new__(cls, name, bases, dct)

class MyClass(metaclass=Meta):
    pass

When declaring MyClass, it will output: Creating class MyClass.

Thus, metaclasses provide a powerful tool for metaprogramming in Python.