This is the 21st day of my participation in the August More Text Challenge

What is a metaclass

In Python, everything is an object. We define numbers, strings, functions, lists, and so on as objects. Objects are instances of classes, and classes are objects, instances of Type. This type is the Metaclass in Python. Metaclasses are classes used to create all types, and all new classes in Python and all classes in Python3 are instances of type metaclasses. Let’s look at this example:

print(type(0))  # <class 'int'>
print(type(int))  # <class 'type'>
print(type("tigeriaf"))  # <class 'str'>
print(type(str))  # <class 'type'>
print(type([1.2.3]))  # <class 'list'>
print(type(list))  # 
      

class User:
    pass
u = User()
print(type(u))  # <class '__main__.User'>
print(type(User))  # <class 'type'>
print(type(type))  # <class 'type'>
Copy the code

The type metaclass creates classes dynamically

In addition to defining classes to use the class keyword, we can also use type to create classes dynamically. It is used as follows: type(name, bases, dict), which takes three arguments

  • The first parameter name is the name of the class to be created
  • The second argument, bases, refers to the tuple that needs to inherit from its parent
  • The third dict argument is an attribute of the class

Such as:

class User:

    def __init__(self) :
        self.name = 'tigeriaf'

print(User)
user = User()
print(user.name)
Copy the code
User = type('User', (), {'name': 'tigeriaf'})
print(User)
user = User()
print(user.name)
Copy the code

You can create classes in either of these ways, and the output is the same. It is also very convenient to create classes dynamically using Type.

Custom metaclasses

We know from the above example that we can use type(name, bases, dict) to create a class. If the type metaclass does not satisfy our requirements, can we define a metaclass and use it to create a class? The answer is yes, and let’s take a look:

class MyMetaClass(type) :

    def __init__(cls, name, bases, dict) :
        super().__init__(name, bases, dict)

        cls.int_attrs = {}

        for k, v in dict.items():
            if type(v) is int:
                cls.int_attrs[k] = v


User = MyMetaClass('User', (), {'name': 'tigeriaf'."age": 24."level": 2."introduction": "Python Full Vegetable Engineer"})
print(User)  # <class '__main__.User'>
user = User()  
print(user.name)  # tigeriaf
print(user.int_attrs)  # {'age': 24, 'level': 2}
Copy the code

You can also use the following method to create classes that inherit from metaclasses.

class User(metaclass=MyMetaClass) :
    pass
Copy the code

Note: using metaclasses in Python2 requires an assignment of __metaclass__ to the metaclass in the class to be created.

This code defines a class MyMetaClass that inherits from type. Since Type is a metaclass, MyMetaClass is also a metaclass. __init__ calls the parent type’s __init__() method via super().__init__(name, bases, dict). In addition to implementing the custom metaclass, the attributes are looped through when the class is created, and the attributes of type int are stored separately. Now we have a more customized metaclass than the Type metaclass, and we can add whatever functionality we want to the metaclass.

conclusion

Overall down, found that yuan class and use some difficult to understand and don’t see any special place to let us to use, well, that’s true, normally does may not use it, in fact, yuan class is mainly play a role in class and instance creation, to implement some functions, if really don’t know when to go, that we don’t need it, We may find it powerful when we really need it.

Finally, thank my girlfriend for her tolerance, understanding and support in work and life!