Python Learning note Eight object-oriented advanced Programming (ii) Meta-class

Source: Internet
Author: User
Tags class generator

Reference Tutorial: Liao Xuefeng official website https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

In the teacher Liao's study website "Use meta-class" This part or to see me dizzy ... On the internet to find a feeling to speak relatively easy to understand some, posted links: Two words grasp the most difficult knowledge of Python-the meta-class-with this article as the source of this note.

"Daosh One, life two, two three, Sansheng everything"

1, in the Python world, "type" is the Tao, which is the origin of all kinds of classes, objects, variables and so on.

2, one-that is, Metaclass (meta-class, also known as the class generator)

3, two--that is, a variety of regular classes (class)

4, three--that is, example (instance)

5, all things--that is, the various properties and methods of the example

# Create a student class, which is "two" class Student (): def Printinfo (self):         Print ("It is a instance of student!" # Create An instance of Student s, which is the "two-born three"S=student ()# Use the properties, methods of the instance,           That is "Sansheng everything"s.printinfo ()

This code extracts from two to the process of everything, then for the student class this "two" from where?

We see the definition of Class Student () ... These codes, in fact, are as follows:

def fn (self):     Print ("It is a instance of student! " ) Student=type ('Student', (object,), Dict (PRINTINFO=FN))

Notice here that the student class is generated by the type () method, which has three parameters, namely the name of the set class, the parent class of the class using a tuple, and a dictionary to give the Class A method.

Type is "Tao", you can first generate a meta-class, and then the meta-class to generate a variety of classes.

"Meta-class"

In general, the meta-class is named suffix Metaclass.

Let's start with an example of defining a meta-class: Suppose you need a meta-class that can be greeted automatically, and its class methods sometimes need to be say_hello, sometimes need to be say_hi, and sometimes need to be say_sayolala, sometimes say_nihao.

class Saymetaclass (type):  # Note that the Meta class inherits from type    def__new__(cls,name,bases, Attrs):        attrs['say_'+name]=Lambda self,value,saying=name: Print (saying+','+value+'! ' )        return type. __new__ (Cls,name,bases,attrs)

Attention:

1, the meta-class is derived from the "type", so the parent class must pass in the type.

2, the operation of the meta-class is done through __new__ (), the first parameter is the object of the class that will be created (is basically similar to self?), the following three parameters are: class name, parent class, property/method.

See this code specifically:

attrs['say_'+name]=Lambda self,value,saying=name:print(saying+  ','+value+'! ')

Here is a property for each class to define a "' Say_ ' + class name," Here is a method, through the lambda definition method, this method has three parameters, the first self, because it is a method of the class, so it must be the first self, the second is the general position parameter value, The user is required to pass in, and the third is a default parameter, which defaults to the class name.

The classes continue to be produced through this meta-class:

classSaymetaclass (type):#Notice that the meta-class inherits from the type    def __new__(cls,name,bases,attrs): attrs['Say_'+name]=LambdaSelf,value,saying=name:Print(saying+','+value+'!')        returnType.__new__(cls,name,bases,attrs)#Create a Hello class from Saymetaclass#Note that in addition to the first parent class, the parameter must be marked with a metaclass= to indicate the class used by the#because the class name here is Hello#so this Hello class has a property of "Say_hello"#This property is also a method that is equivalent to the following code:" "def say_hello (self,value,saying= ' Hello '): Print (saying+ ', ' +value+ '! ')" "classHello (object,metaclass=saymetaclass):PassHello (). Say_hello (' World')  #continuing to create a new class based on a meta-classclassNihao (object,metaclass=saymetaclass):PassNihao (). Say_nihao (' China') Nihao (). Say_nihao (' China', saying='Very Great') #continuing to create a new class based on a meta-classclassSayolala (object,metaclass=saymetaclass):PassSayolala (). Say_sayolala ('Japan')

The output is as follows:

hello,world! nihao,china! Very great,china! sayolala,japan!

Python Learning note Eight object-oriented advanced Programming (ii) Meta-class

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.