Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine a class's metaclass in Python 3

In Python 2, I could check a class's __metaclass__ attribute to determine its metaclass.

How do I the same thing in Python 3?

like image 337
Neil G Avatar asked Aug 15 '12 14:08

Neil G


People also ask

What is __ metaclass __ in Python?

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.

How do you set the metaclass of class A to B?

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.

How do you use meta classes in Python?

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.

What is __ add __ in Python?

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.


1 Answers

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
like image 132
ecatmur Avatar answered Nov 14 '22 22:11

ecatmur