How are Python metaclasses different from regular class inheritance? [duplicate]

The difference is that inheriting from a class does not affect how the class is created, it only affects how instances of the class are created. If you do:

class A(object):
    # stuff

class B(A):
    # stuff

then A does not have any opportunity to “hook in” when B is created. Methods of A may be called when an instance of B is created, but not when the class B itself is created.

Metaclasses allow you to define custom behavior for when a class is created. Refer to the question I marked as duplicate for examples of how metaclasses work, and convince yourself that there are effects in those examples that you can’t achieve with normal inheritance.

Leave a Comment