Understanding and simple use of Python classes and meta-classes (Metaclass)

Source: Internet
Author: User

(i) Classes in Python

First, the Python classes discussed here are based on modern classes that inherit from object.

First in Python, everything is an object. It's very important to understand the meta-class. I'm going to try to understand the classes in Python.

class Trick (object):     Pass

When Python executes the band class statement, it initializes a class object to be placed in memory. For example, a trick object is initialized here

This object (class) itself has the ability to create objects (often we say instances, but in Python or objects).

To facilitate subsequent comprehension, we can first try the oldest and most powerful keyword type in the new class.

Input
class Trick (object):
Pass  Print type ('123')print type (123)print Type (Trick ())

Output
<type ' str ' >
<type ' int ' >
<class ' __main__. Trick ' >

You can see the str, int, and an instance object we initialized trick () that we normally use.

But the following methods you may not have seen, type can also be used to dynamically create a class

Type(the class name , the tuple of the parent class (which can be empty for inheritance), the dictionary that contains the property (name and value))

How does this work, I'm going to use this method to create a class let's look at the following code

Input: print type ('trick', (), {}) Output:<class'__ Main__.trick'>

Again, we can instantiate this class of objects

Input: print type ('trick', (), {}) Output:<__main__ . Trick Object at 0x109283450>

As you can see, this is a trick instance object.

The same method can also initialize the parent class of the created class, as well as initialize the class properties:

Input:classFlytosky (object):PassPW= Type ('Trick', (Flytosky,), {'Laugh_at':'Hahahaha'})PrintPW (). Laugh_atPrintpw.__dict__Printpw.__bases__PrintPW ().__class__PrintPW ().__class__.__class__output:hahahaha{'__module__':'__main__','Laugh_at':'Hahahaha','__doc__': None} (<class '__main__. Flytosky'>,)<class '__main__. Trick'><type'type'>

I'll take a look at the above, and I'll start by introducing two magical methods:

1. __class__ This method is used to see which object belongs to which build, so that everything in Python is an object, and the class object is also an object. The class is an instance of the Meta class, and the instance object is an instance of the class, if you think about it as you thought before.

2. __bases__ This method is used to get the parent class of an object who is, in particular note that __base__ returns a single parent class, __BASES__ returns all the parent classes as a tuple.

Okay, now that I know these two methods, let me say what each line means.

1. Use type to create a class to assign a value to the accepted three parameters of the PW type (the name of the class, whether the class has a parent class (), the class's property dictionary {})

2. Initialize an instance of a class here, then try to get the Laugh_at property value of the parent class, and then get the result hahahaha

3. Take a PW of the class dictionary data of our common class

4. Get the parent of PW, and the result is our designated Flytosky

5. The instance of PW () PW () belongs to which class is initialized, and can be seen as Class Trick

6. Let's see who initialized the class trick? is the meta-class type.

(b) What is a meta-class and simple application

After all this introductions, we can finally get to the chase.

What is a meta-class? In layman's words, a meta-class is a class that creates classes ... Does that sound like a super-abstract?

Take a look at this.

Trick == Trick ()

We've already introduced it, and a trick can do it directly.

Trick = Type ('Trick', (), {})

This is actually because the type is actually a meta-class, which he can use to create classes. What is a meta-class just now, the meta-class is the class that created the class. It can also be said that he is a class of the creation of factories.

Class above the __metaclass__ attribute, believe that willing to understand the meta-class details of the pot friends, have certainly seen this thing, and for it curiosity. Or I don't know what it is that supports you to see the??。 here. Using the __metaclass__ method means that the class is created with the __metaclass__ specified by the Meta class.

class Trick (Flytosky):     Pass

When we created the class above, Python did the following:

Is there __metaclass__ this attribute in trick? If so, Python creates a class object named trick in memory by __metaclass__, which is trick. If Python does not find __metaclass__, it will continue to look for the __metaclass__ property in its parent class Flytosky, and attempt to create a trick class object in the __metaclass__ specified method. If Python does not find __metaclass__ in any of the parent classes, it does not abandon it, but instead searches the module for a __metaclass__ designation. If you still can't find it, all right, that is, use the default type to create the trick.

So the question is, what are we going to put in the __metaclass__? The answer is something that can create a class, type, or anything that uses the type or subclass type.

(iii) custom meta-classes

The purpose of the custom class, I summed up is to block the creation of the class, and then modify some features, and then return the class. Is it a little familiar? Yes, it is the feeling that the decorator is doing, but the decorator is a function that modifies the same thing, and then adds something to it, and finally gets returned.

In fact, in addition to the above-mentioned formulation of a __metaclass__ does not need to be assigned to it is not necessarily a formal class, is a function can also. To create a class that allows all module levels to be created with this meta-class, set the __metaclass__ at the module level. First write one to try, I still use stackoverflow above that Buddy's example, all the attributes are changed to uppercase.

Take a look at this example:

Input:defupper_attr (class_name, Class_parents, class_attr):"""returns an object that changes the property to uppercase:p Aram Class_name: The name of the class:p Aram Class_parents: The parent of the class tuple:p Aram class_attr: Parameters of the class: R Eturn: Return class"""    #generates a generatorAttrs = ((name, value) forName, valueinchClass_attr.items ()if  notName.startswith ('__')) Uppercase_attrs= Dict ((Name.upper (), value) forName, valueinchattrs)returntype (class_name, class_parents, Uppercase_attrs)__metaclass__=UPPER_ATTRPW= Upper_attr ('Trick', (), {'Bar': 0})PrintHasattr (PW,'Bar')PrintHasattr (PW,'BAR')PrintPW. Baroutput:falsetrue0

As you can see from the above, I implemented a meta class (Metaclass) and then specified that the module use this meta class to create the class, so when I use the type to create the class below, I can find that the lowercase bar parameter is replaced with the uppercase bar parameter, and at the end I call the Class property and, Print it out.

Above we used the function to do the Meta class passed to the class, below we use a formal class to pass as a meta class to __metaclass__

classUpperattrmetaclass (type):def __new__(MCS, class_name, Class_parents, class_attr): Attrs= ((name, value) forName, valueinchClass_attr.items ()if  notName.startswith ('__')) Uppercase_attrs= Dict ((Name.upper (), value) forName, valueinchattrs)returnSuper (Upperattrmetaclass, MCS).__new__(MCS, class_name, Class_parents, Uppercase_attrs)classTrick (object):__metaclass__=Upperattrmetaclass Bar= 12 Money='Unlimited'PrintTrick.barPrintTrick.money

Summarize:

Ah good tired and tired finally finished ... Wrote for a long time, in short, as I said above, a little bit of decorative ideas to understand the meta-class this thing, may let you suddenly enlightened. Meta-class This dark magic should not be widely used in common sense, from writing business code for almost a year, in addition to the completion of the Kepler project is a little bit dark magic (actually do not need to do so), other places have not been used. When you really need it, you may not think about why you want to use it, but because you want to solve the problem so it is written so that there is a meta-class thing. I understand that the real meaning of the existence of a thing is that you can use it to solve problems that have been difficult to solve before, to make it easier to solve problems, rather than to complicate a problem for the sake of dazzle.

Reference:

HTTP://BLOG.JOBBOLE.COM/21351/deep understanding of the meta-classes in Python

Http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python What's metaclass in Python

Understanding and simple use of Python classes and meta-classes (Metaclass)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.