Use metaclasses

It’s finally time to use metaclasses, but generally speaking, we don’t use them at all. As Tim Peters, the leader of the Python community, said:

Metaclasses are the magic of depth, 99% of them Users shouldn't have to worry about this at all. If you're trying to figure out whether you need a metaclass, you don't need it. Those who actually use metaclasses know exactly what they need to do and don't need to explain why they are used at all.

The main purpose of metaclasses is to create APIs. A typical example is Django ORM. It allows you to define it like this:

class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

But if you do this:

guy  = Person(name='bob', age='35')
print guy.age

This will not return an IntegerField object, but will return an int, or even directly Get data from the database. This is possible because models.Model defines __metaclass__ and uses some magic to turn the simple Person class you just defined into a complex hook to the database. The Django framework simplifies these seemingly complex things by exposing a simple API using metaclasses, through which the code is recreated and the real work is done behind the scenes.

Everything in Python is an object, they are either instances of a class or a metaclass, except type. type is actually its own metaclass, which is something you can't do in a pure Python environment. It's done through some trickery at the implementation level.

Continuing Learning
||
submitReset Code