python-in-depth understanding of meta-classes (Metaclass)

Source: Internet
Author: User
Tags class definition

1. Dynamically create a class using type (type is a class that is used to create a class object's meta-class, so it can also be inherited )

Type ("person", (), {"name""John" })

2. Meta-class

The classes in Python are also objects, and the meta-class is the class that creates these class objects, which can be understood as

MyClass == MyClass ()

3.type is actually a meta class, type is the meta-class that Python uses to create all classes, like STR is the class that creates the string object, int is the class that creates the integer, and the type is the class that creates the class

Everything in 4.Python is an Object!

>>> age = 35>>>.__class__<type‘Int' >>>> name =‘bob ">>> name. str  ">>>> def foo (): pass>>>foo. __class__<type   Function ">>>> class Bar (object): pass>>> b = Bar () >>> b.__class__ <class  __main__. Bar

What about the __class__  property for any one __class__ ?

 >>> a.__class__ . __class__  <type  " type   >>>> age. __class__ . __class__  <type  " type   " >>>> foo. __class__ . __class__  <type  " type   " >>>> b.__class__ . __class__  <type  " type  ; 

Conclusion: A meta-class is something that creates a class object, type is the inner Jianyuan class of Python (xx.__class__.__class__ is type)

5.__metaclass__ Property

You can add a __metaclass__ property to a class when you write it

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

If you do this, Python will use the Meta class to create Class Foo, be careful, there are some tricks, you first write class Foo (object), but the class object Foo has not been created in memory, Python will look for the __metaclass__ attribute in the class definition, and if found, Python will use it to create the class Foo, and if not found, create the class with the built-in type .

6. In-depth understanding of the __metaclass__ in the previous step

class Foo (Bar):     Pass

Is there a __metaclass__ attribute in Foo? If so, Python will create a class object named Foo in memory via __metaclass__ (I'm talking about class objects, follow my lead), and if Python doesn't find __metaclass__, it will continue to look for __ in bar (parent class). Metaclass__ property, and try to do the same as before, if Python is not found in any parent class __metaclass__, it will be in the module hierarchy to find __metaclass__, and try to do the same, if you still can't find __ metaclass__, Python will use the 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 something of a class object, so what can be used to create a class? Type, or anything that uses the type or subclass type (like 1 to create a class object using type)

7. Custom meta-classes

Condition: The properties of all classes in the module should be in uppercase form

Implementation (__metaclass__ can actually be arbitrarily called, it does not need to be a formal class):

#the meta-class automatically passes the arguments you normally pass to ' type ' as your own argumentsdefupper_attr (Future_class_name, Future_class_parents, future_class_attr):" "returns a class object that converts properties to uppercase" "    #Select all properties that do not start with ' __ 'Attrs = ((name, value) forName, valueinchFuture_class_attr.items ()if  notName.startswith ('__'))    #convert them to uppercaseUppercase_attr = Dict ((Name.upper (), value) forName, valueinchattrs)#create a Class object by ' type '    returntype (future_class_name, future_class_parents, uppercase_attr)__metaclass__= Upper_attr#This will work for all classes in this module classFoo (object):#We can also define __metaclass__ only here, so that it only works in this class .Bar ='Bip'PrintHasattr (Foo,'Bar')#Output: FalsePrintHasattr (Foo,'BAR')#Output: TrueF=Foo ()PrintF.bar#output: ' Bip '

Implemented in OOP:

#keep in mind that ' type ' is actually a class, just like ' str ' and ' int '#So, you can inherit from typeclassUpperattrmetaclass (type):#__new__ is a special method that is called before __init__    #__new__ is the method used to create an object and return it    #The __init__ is simply used to initialize the passed parameters to the object    #you rarely use __new__ unless you want to be able to control the creation of objects    #here, the object created is the class, we want to be able to customize it, so here we rewrite __new__    #If you want, you can do something in __init__ .    #There are some advanced uses that involve rewriting __call__ special methods, but we don't have to    def __new__(Upperattr_metaclass, Future_class_name, Future_class_parents, future_class_attr): Attrs= ((name, value) forName, valueinchFuture_class_attr.items ()if  notName.startswith ('__')) Uppercase_attr= Dict ((Name.upper (), value) forName, valueinchattrs)returnType (Future_class_name, future_class_parents, uppercase_attr)

8. Why use meta-classes?

Now back to our big theme, why are you going to use such an error-prone and obscure feature? Well, generally speaking, you don't use it at all:

"Meta-class is the magic of depth, 99% of users should not worry about it at all." If you want to figure out whether you need to use a meta-class, then you don't need it. Those who actually use the meta-class know very well what they need to do and do not need to explain why they use the meta-class at all. "The leader of the--python world Tim Peters

The main purpose of the meta-class is to create an API, a typical example of which is the Django ORM, which allows you to define like this:

class Person (models. Model):    = models. Charfield (max_length=30)    = models. Integerfield ()

But if you do it like this:

Guy  = person (name='bob', age=')Print Guy.age

This does not return an Integerfield object, but instead returns an int that can even fetch data directly from the database, which is possible because of models. The model defines __METACLASS__ and uses some magic to transform the simple person class you just defined into a complex hook to the database, and the Django framework exposes these seemingly complex things by exposing a simple API that uses meta-classes to simplify them. Recreate the code through this API and do the real work behind the scenes

9. Summary

Everything in Python is an object, either an instance of a class or an instance of a meta class, except for type, which is actually its own meta-class

Excerpt from: http://python.jobbole.com/21351/

python-in-depth understanding of 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.