"Python advanced" detailed meta-class and its application 2

Source: Internet
Author: User

Objective

In the previous article, "Python Advanced", the meta-class and its Application 1, we mentioned some of the meta-class of the pre-knowledge, introduced the class object, dynamically create the class, using the type to create the class, this section we will continue to the above ~ ~ ~ ~

5. Type create a class with a method

Eventually you will want to add a method to your class. You just need to define a function with the proper signature and assign it as a property.
Add an instance? method

In [14]:defEcho_bar (self):#defines a normal function....:Print(Self.bar) ...: in [[]: Foochild = Type ('Foochild', (Foo,), {'Echo_bar': Echo_bar}) in [[+]: hasattr (Foo,'Echo_bar')#determine if there is a Echo_bar attribute in the Foo classOut[16]: Falsein [+]: hasattr (Foochild,'Echo_bar')#determine if there is a Echo_bar attribute in the Foochild classOut[17]: Truein []: my_foo=foochild () ...: in [19]: My_foo.echo_bar () True

Add static method

in [20]: @staticmethod ...:defteststatic (): ...:Print("static method ....") ...: in []: Foochild=type ('Foochild', (Foo,), {"Echo_bar": Echo_bar,"teststatic": Teststatic}) in [[]: fooclid=Foochild () in [23]: fooclid.teststaticout[]: <function__main__.teststatic>In [24]: fooclid.teststatic () static method .... in [25]: Fooclid.echo_bar () True

Add Class? method

in [26]: @classmethod ...:defTestClass (CLS): ...:Print(Cls.bar) ...: in [+]: Foochild=type ('Foochild', (Foo,), {"Echo_bar": Echo_bar,"teststatic": Teststatic,"TestClass": TestClass}) in [: Fooclid =Foochild () in [29]: Fooclid.testclass () True

As you can see, in Python, classes are also objects, and you can create classes dynamically. This is what Python does behind the scenes when you make the keyword class, and this is done through the Meta class.

6. What is a meta-class (finally to the topic)

The meta-class is the "East?" of the class to create. You create a class just to create an instance object of the class, don't you? But we've learned that the classes in Python are also objects.
The meta-class is the class that creates these classes (Objects ), which you can understand as:

MyClass = Metaclass ()#MyObject = MyClass ()# so? " Class "To create an instance object

You've seen the type that allows you to do something like this:

Myclass=type ('MyClass', (), {})

This is because the function type is actually a meta class. Type is python behind? To create a meta class for all classes. Now you want to know why the type will be all right? Written form? Well, I guess this is to keep it with Str. What is STR? A class that creates a string object, an int is a class that creates an integer object. Type is the class that creates the class object. You can see this point by checking the __class__ property. all the east of Python, note that I mean all the east?—— are objects. This includes integers, strings, functions, and classes . All of them are objects, and they are all created from a class, and this class is type.

in [+]: Age = 35In [+]: Age.__class__out[31]: Intin [+]: name ='Bob'In [[]: Name.__class__out[33]: Strin [34]:deffoo (): ....:Pass...: in [+]: Foo.__class__out[35]: Functionin [36]:classBar (object): ...:Pass...: in [PNS]: b =Bar () in [(a): B.__class__out[38]:__main__. Bar

Now, what is the __class__ attribute for any __class__?

in [+]: name. __class__. __class__ out[]: Typein [+]: Age. __class__. __class__ out[]: Typein []: foo. __class__. __class__ out[]: Typein []: B.__class__. __class__ out[]: type

Therefore, the meta-class is the east of the object that created the class. Type is Python's inner Jianyuan class, of course, you can also create?? Meta-class.

7.__metaclass__ Property

You can add the __metaclass__ property to a class when you define it.

class Foo (object):       __metaclass__ = something      ... ... Omit ...

If you do this, Python will be the Meta class to create class Foo. Dot, this?? Some tricks. You write the class Foo (object) First, but the class Foo is not yet created in memory. Python will look for the __metaclass__ attribute in the definition of the class, and if it does, Python will? It creates the class Foo, and if it is not found, the built-in type to create the class. Read this passage over and over again. When you write the following code:

class Foo (Bar):    ...:     pass    ...:

Python does the following:

    1. Is there a __metaclass__ attribute in Foo? If so, will python create it through __metaclass__? A Class (object) with the name Foo
    2. If Python does not find __metaclass__, it will continue to look for the __metaclass__ attribute in bar (? Class) and try to do the same thing as before.
    3. If Python cannot find __metaclass__ in any of the classes, it will look for __metaclass__ in the module hierarchy and try to do the same.

    4. What if you can't find __metaclass__,python? Built-in type to create this class object.

Now the question is, what code can you put in the __metaclass__? The answer is: You can create a class of East? So what can I do to create a class? Type, or anything that makes it to type or to a class type.

8. Define a meta-class

The main purpose of the meta-class is to be able to change classes when creating classes. Typically, you do things like this for the API, and you want to create classes that match the current top and bottom.
A silly example? Do you decide on your module? All the properties of the class should be written. There are good ways to do it, but one of them is to set __metaclass__ at the module level. All of the classes in this module are created by this meta-class, and we just need to tell the meta-class to change all the attributes to the writing form.
Fortunately, __metaclass__ can actually be arbitrarily tuned, and it doesn't need to be a formal class. So, we're going to start with a simple function as an example.

In Python3

#-*-coding:utf-8-*-defupper_attr (future_class_name,future_class_parents,future_class_attr):#iterate through the property dictionary and change the name of the property that is not the beginning of __ to writeNewattr = {}     forName,valueinchFuture_class_attr.items ():if  notName.startswith ("__"): Newattr[name.upper ()]=value#type to create a class    returntype (future_class_name,future_class_parents,newattr)classFoo (object,metaclass=upper_attr): Bar='Bip'Print(Hasattr (Foo,'Bar'))Print(Hasattr (Foo,'BAR')) F=Foo ()Print(F.bar)

Now let's do it again, this time?? A real class to be used as a meta-class.

#-*-coding:utf-8-*-classUpperattrmetaclass (type):#__new__ is a special method that was transferred before __init__ .    #__new__ is? To create an object and return the method    #__init__ just? To initialize the parameters of a pass to an object    #are you very little? to __new__, except? You want to be able to control the creation of objects    #The object that is created is the class, and we want to be able to define it, so we do this? Rewrite __new__    #If you want, you can do something in __init__ .    #What else? The law will involve rewriting the __call__ special law, but we don't ?    def __new__(cls,future_class_name,future_class_parents,future_class_attr):#iterate through the property dictionary and change the name of the property that is not the beginning of __ to writeNewattr = {}         forName,valueinchFuture_class_attr.items ():if  notName.startswith ("__"): Newattr[name.upper ()]=value#Method 1: Create a Class object by ' type '        #return type (future_class_name,future_class_parents,newattr)                #Law 2: Re-type.__new__ Law        #This is basic OOP programming, no magic .        #return type.__new__ (cls,future_class_name,future_class_parents,future_class_attr)        #Law 3: The Super Law        returnSuper (UPPERATTRMETACLASS,CLS).__new__(cls,future_class_name,future_class_parents,future_class_attr)#Python2 's Law .#class Foo (object):#__metaclass__ = upper_attr# The meta class of the Foo class is upper_attr#bar = ' Bip '#Python3 's Law .classFoo (object,metaclass=upper_attr): Bar='Bip'Print(Hasattr (Foo,'Bar')) #Output: FalsePrint(Hasattr (Foo,'BAR')) #Output: Truef =Foo ()Print(F.bar)#output: ' Bip '

That's it, besides, there's really nothing else to say about the meta-class. But in the meta-class itself???, they are actually very simple:

    1. Block creation of classes
    2. Modifying a class
    3. Returns the class after the modification

Why should we make the meta-class?

Now go back to our theme, what exactly is it that you're going to make? This kind of error-prone and obscure feature? Well, like, you're not going to do it at all:
"Meta-class is the magic of depth,99% of the households should not do this at all?" If you want to figure out whether you need it or not, then you don't need it. What are the actual and meta-classes? often know exactly what they need to do, and don't need to explain why. Meta class. "The leader of the--python world timpeters

"Python advanced" detailed meta-class and its application 2

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.