In Python 2, I could check a class's __metaclass__
attribute to determine its metaclass.
How do I the same thing in Python 3?
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.
In order to set metaclass of a class, we use the __metaclass__ attribute. Metaclasses are used at the time the class is defined, so setting it explicitly after the class definition has no effect.
To create your own metaclass in Python you really just want to subclass type . 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.
Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator “+” in Python.
Use the single-argument type
function (type(class)
), or just access class.__class__
. Both of these work in Python 2, btw.
E.g.,
In [4]: class MyMetaclass(type): pass
In [5]: class MyClass(metaclass=MyMetaclass): pass
In [6]: type(MyClass)
Out[6]: __main__.MyMetaclass
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