This might be too much of an open ended question, but I'm just now learning about metaclasses in Python and I don't understand how a metaclass is any different than just having a child class inherit from the parent class, like
class child(parent):
Wouldn't this serve the same purpose of a metaclass? I guess maybe I don't understand the purpose of a metaclass.
Principially, metaclasses are defined like any other Python class, but they are classes that inherit from "type". Another difference is, that a metaclass is called automatically, when the class statement using a metaclass ends.
A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass.
A metaclass in Python is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes.
The term metaprogramming refers to the potential for a program to have knowledge of or manipulate itself. Python supports a form of metaprogramming for classes called metaclasses. Metaclasses are an esoteric OOP concept, lurking behind virtually all Python code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With