Introduction to the

  • Goal: After a subclass inherits from a base class, it can obtain all of its subclasses from the base class.
  • Meaning: There is no need for subclasses to perform the registration operation. All subclasses can be managed through the base class.
  • Example: SQLAlchemy database management, inheriting base classes will be automatically discovered by migration.

implementation

Build a metaclass

class BaseMetaClass(type) :
    Metaclasses control the creation of classes, which execute the __new__ method of the metaclass. Based on this mechanism, subclasses can be registered into the class properties of BaseMetaClass during new. "" "

    record_cls = []

    def __new__(mcs, name, bases, attrs) :
        new_cls = type.__new__(mcs, name, bases, attrs)
        If the subclass name is Base, it will not be registered
        if name not in ["Base"]:
            BaseMetaClass.record_cls.append(new_cls)
        return new_cls
Copy the code

To build a base class

class Base(object, metaclass=BaseMetaClass) :
    pass
Copy the code

Build a subclass

class MyClass(Base) :
    pass
Copy the code

Knowledge extension

The creation behavior of aclass can be controlled with the Metaclass parameter

Class Book(BaseBook, metaclass=BookMetaClass), etc., can control the creation behavior of the Book class. Write the concrete logic in the bookmetaclass.__new__ method that will automatically execute the metaclass’s new method on the above line of code.

The essence of creating a class is to create type objects

The equivalent of class Book(BaseBook) is Book = type(“Book”).

So the process of creating the Book class is similar to the process of creating the Book object, except that the process of creating the Book class performs “new of the metaclass BookMetaClass”, and the process of creating the Book object performs “Book’s own new and Book’s own init”.

The specific process for creating classes and class objects is as follows:

  • Launches the program, executes to the class Book line, creates the class, and executes the metaclass new method of the class
  • Execute to the Book() line, at which point you create the class object and execute the class’s own new method, which returns the class object
  • The new method in step 2 automatically callback the class’s own init method when it returns a class object

Refer to the link

  • Python automatically registers subclasses
  • Use metaclass — Liao Xuefeng