Understanding of the Meta-Class (Metaclass) in Python

Source: Internet
Author: User

A: Class is also an object

A class is a set of code to describe how to generate an object.

A class is also an object, as long as you use the keyword Class,python interpreter to create an object when it executes.

The following code:

class Objectcreator (object):     Pass

An object is created in memory, the name is Objectcreator, and the object (class) itself has the ability to create objects (class instances).

The essence of a class is an object, you can copy it, you can assign it to a variable, pass it as an argument to a function, and you can add properties to it.

The following are examples:

classObjectcreator (object):PassPrint(Objectcreator)#Print a classdefEcho (data):Print(data) echo (Objectcreator)#passing a class as a parameter to a functionObjectcreator.newattribute='New attr'  #to add a new property to a classPrint(Hasattr (Objectcreator,'Newattribute'))Print(objectcreator.newattribute) objectcreatorcopy= Objectcreator#To copy a class to a variablePrint(objectcreatorcopy)Print(Objectcreatorcopy ())" "output: <class ' __main__. Objectcreator ' ><class ' __main__. Objectcreator ' >truenew attr<class ' __main__. Objectcreator ' ><__main__. Objectcreator object at 0x0000000001ea9860>" "

Second: Dynamic creation of classes

1 classes required by the return class dynamic construction

Classes are also objects, so we create them dynamically when we run them again. To create a class in the function body:

defCreate_class (name):ifName = ='Foo':        classFoo (object):Pass        returnFooElse:        classBerry (object):Pass        returnBerrymy_class= Create_class ('Foo')Print(My_class)#Return classPrint(My_class ())#returns an instance of a class    " "output: <class ' __main__.create_class.<locals>. Foo ' ><__main__.create_class.<locals>

2 Constructing a class by using the type function

The above method requires you to write your own code for the entire class. Because the class is also an object, it must be generated by something.

The built-in function type lets you know what type of an object is, like:

class Demo (object):     Pass Print (Type (+)) Print (Type ('str')) Print (Type (Demo)) Print (Type (Demo ())) " " output: <class ' int ' ><class ' str ' ><class ' type ' ><class ' __main__. Demo ' > '

In addition, the type can dynamically create classes. The type can receive a description of a class as a parameter and then return a class.

Syntax for type:

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))

For example, the following code:

class Myclassdemo (object):     Pass # can be manually created from type  = Type ('myclassdemo'# Returns a class object print( Myclassdemo)print(Myclassdemo ())" output: <class ' __main__. Myclassdemo ' ><__main__. Myclassdemo object at 0x000000000213a3c8>'

Here's an example of how the type is created:

#1 building Foo classclassFoo (object): Bar=True#Build with TypeFoo = Type ('Foo', (), {'Bar': True})Print(Foo)#2 inheriting the Foo classclassFoochild (Foo):Pass#Build with TypeFoochild = Type ('Foochild', (Foo,), {})Print(Foochild)Print(Foochild.bar)#3 Adding methods to the Foochild classdefEcho_bar (self):Print(Self.bar) Foochild= Type ('Foochild', (Foo,), {'Echo_bar': Echo_bar})Print(Hasattr (Foo,'Echo_bar'))Print(Hasattr (Foochild,'Echo_bar')) My_foo=Foochild () My_foo.echo_bar ( )" "output: <class ' __main__. Foo ' ><class ' __main__. Foochild ' >truefalsetruetrue" "

As you can see, in Python

Understanding of the Meta-Class (Metaclass) in Python

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.