Member-only story

Python Tips — Demystifying Python Metaclasses

Tony
3 min readOct 2, 2023

If you’re doing object-oriented programming (OOP) inPython, you’ll come across the concept of metaclasses. And as a DevOps Engineer, knowing how classes (and metaclasses) work in Python can enhance the structure and adaptability of your scripts.

Python Classes

To truly grasp the concept of metaclasses, one must first delve deeper into Python’s notion of classes. Python’s understanding of classes is somewhat unique, influenced by the Smalltalk programming language.

In many programming languages, classes simply define the blueprint for creating an object. This perspective holds somewhat true for Python as well. But classes are more than that in Python. Classes are objects too.

When the Python interpreter encounters the class keyword, Python creates an object out of the "description" of the class that follows. For example:

>>> class Car:
... pass
...
>>> my_car =Car
>>> my_car.name = "car"
>>> print(my_car)
<class '__main__.Car'>
>>> print(my_car())
<__main__.Car object at 0x7fdec5f9bc50>

As you can see, the definition of

class Car:
pass

creates an object with the name Car, and this object itself (class) is capable of creating other objects (instances).

--

--

Tony
Tony

No responses yet