Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the python metaclass and how to use it

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces what the python metaclass is and how to use the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you read this python metaclass is what and how to use the article will have a harvest, let's take a look.

A class in python is also an object, which can be said to be a class object, which can be created by type (). With this knowledge, let's take a look at the following function:

This can specify the generation of related objects according to the parameters we pass, which can be said to be very simple to create classes dynamically. Let's take a look at the results:

The parameter entered here is user, so the best result is to generate the User class. Although this method is simple, when there is more and more logic in the class, there will be a lot of code written in the class, and it will become very bloated and not good-looking, so this method is not appropriate.

Let's take a look at the type () method, which said it can create a class dynamically, so now let's see how to create it.

On the pycharm editor, go to the internal source code of type () and see:

The third line is to create a new class that receives three parameters, and the meaning of these three parameters is easily known by name:

Name: the name of the class

Bases: base class, which is the class that needs to be inherited

Dict: properties of the class, including methods

Well, now that we know, let's create one and have a look.

You can see that I created a person class without a base class. Notice that the base class receives a tuple, and the property has only one name property. Is this simple and straightforward? if you need to add a method, just add the corresponding method name to the dict parameter, as follows:

We know that the class that can create a class is a metaclass, so type is also a metaclass. This is relatively simple, because only three parameters, according to the rules, but this can only dynamically generate the class, can not operate on the class generation process, that is to say, can not control how the class is generated, so in python3 there is a metaclass: metaclass, this is also a dynamic creation of classes, than type this method can operate more things, but also a bit difficult.

Before we talk about metaclass, let's talk about how classes are generated. There are two kinds of classes.

Ordinary classes, not created through metaclass, this is simple, is through type to create class objects.

The second is to use metaclass, which creates a class through metaclass. If there is no such class, it will look for the metaclass of the parent class, and it will continue to look up until it is found.

Again, why use metaclass to create classes?

The process of creating a class object is delegated to the metaclass, and there is no need to operate inside the class, so the code is more separate.

You can check whether the class has those abstract methods that implement the parent class. If there is no overload, you can throw an exception directly to prevent the creation from being successful.

There are many more, which will be added later, and you will see that many frameworks will use metaclass to create classes. To be a good python engineer, metaclass must pass.

Having said that, give me a little chestnut to illustrate how to use metaclass to create classes.

As you can see, if you specify metaclass in the class to control the generation of the class, the metaclass you point to must inherit the class t ype. We also control the implementation of the class by modifying the _ _ new__ method in the metaclass class, so we can separate the _ _ init__ and _ _ new__ methods.

Only when there is advertising, there is better output.

Let's demonstrate the benefits of creating a class through a metaclass by implementing an orm framework class. Because everyone knows that it is annoying to use pymysql library to operate mysql in python, this is why we have this orm framework. Here is a quote from Liao Xuefeng's official website:

The full name of ORM is "Object Relational Mapping", that is, object-relational mapping, which maps a row of a relational database to an object, that is, a class corresponds to a table, so that it is easier to write code and does not have to directly operate the SQL statement.

To write an ORM framework, all classes can only be defined dynamically, because only the consumer can define the corresponding classes according to the structure of the table.

Talk is cheap show you the code.

This is what we want to call when using the orm framework. Here we simply define two fields: name and age,User. There is also an internal class Meta, which defines other properties of the data table, separate from the field definition, so a data table name is defined. When saving using the save () method, the mysql statements are internally concatenated, which will be implemented later.

Next, implement the two field classes first.

This is the implementation of the IntField class, you can see a lot of logic in it, and the CharField class is also implemented in this way.

Next is the implementation of metaclass

The method of this _ _ new__ is to control the generation of the class. We can break the point to see what the parameters are.

As you can see, after unpacking, args can be divided into three parameters, one is the class name, the other is the tuple, which is the base class, and the other is the properties of the class, so you can change the above parameters to the following better operation.

Next, we need to extract the fields from the parameters of attrs, but there are many things to judge when judging, for example, we need to judge whether it is CharField or IntField to extract, so that if there are too many fields, we will write a lot of code. One trick is to let all fields inherit a base class Field, and then determine whether it is this base class or not.

This metaclass is basically completed, and finally remember to call the _ _ new__ of the parent class to return, otherwise the creation of the class object will fail and the _ _ init__ method will not be called to instantiate the object.

Another problem here is that users may store field information directly when creating a User, such as the following:

User = User ('Zhang San', 23)

So we also need to implement the _ _ init__ method in the User class, but it won't look good if we add this method directly to the User class. We can implement another base class, BaseModel, and add the _ _ init__ method to this class, which is better, and we can also implement the save () method.

After using another base class, BaseModel, the base class is implemented with metaclass, and User does not need to implement metaclass, but only needs to inherit this base class, because metaclass will look up and only need the parent class implementation. At the same time, in the metaclass Model, we need to add a judgment that only when the class User is created, we need to control the generation of its class, and the rest is not needed.

At this point, let's see how the _ _ init__ method of the base class BaseModel is implemented.

It's much easier to assign values through the setattr () method, and you don't need to judge them one by one and then take them out.

All that is left is the save method, which is much simpler. You only need to implement the concatenation of mysql statements. The statements that need to be concatenated here are

Sql = 'insert user (name, age) values (", 23)'

Take a look at the code implementation.

The above is the implementation of the whole orm framework, doesn't it look very simple? But it solves the complicated mysql operation statements.

Finally, when you run it, you will see a complete mysql statement appear.

If we need to add other types of fields, we just need to implement this class, and we don't need to care about anything else, isn't it super convenient?

This is the end of the article on "what is python metaclass and how to use it". Thank you for reading! I believe you all have a certain understanding of the knowledge of "what is python metaclass and how to use it". If you want to learn more knowledge, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 214

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report