What is metaclass ?

Metaclasses are classes of classes , It's a template for the class

Metaclasses are used to control how classes are created , Just as a class is a template for creating objects , The main purpose of metaclasses is to control the creation behavior of classes

The result of metaclass instantiation is used for us class Defined classes , Just as an instance of a class is an object (f1 The object is Foo An instance of a class ,Foo Class is type An instance of a class )

type yes python A built-in metaclass of , Used to directly control the generated class ,python In any of the class The classes defined are actually type An object instantiated by a class

Mode one : Use class keyword

class Chinese(object):
def __init__(self,name,age):
def talk(self):
print('%s is talking' %self.name)

Mode two : It's manual simulation class The process of creating a class ): Separate the steps of creating a class , Manually create

# preparation :
# Creating classes is mainly divided into three parts
1 Class name
2 The parent of a class
3 The class body
# Class name 
# The parent of a class
# The class body
def __init__(self,name,age):
def talk(self):
print('%s is talking' %self.name)

Step one ( Let's deal with the class body first -> The name space ): The names of class body definitions are stored in the class's namespace ( A local namespace ), We can define an empty dictionary in advance , And then use exec To execute the code of the class body (exec The process of generating a namespace is similar to the real class The process is similar to , It's just that the latter will __ The first attribute is deformed ), Generate the local namespace of the class , That is to fill in the dictionary


Step two : Call metaclass type( You can also customize it ) To generate classes Chinense

Foo=type(class_name,class_bases,class_dic) # Instantiation type Get the object Foo, That is, we use class Defined classes Foo
<class '__main__.Chinese'>
<class 'type'>

We see ,type Receive three parameters :

  • The first 1 The first parameter is a string ‘Foo’, Represents the class name
  • The first 2 The first parameter is a tuple (object, ), Represents all the parent classes
  • The first 3 The first parameter is the dictionary , Here is an empty dictionary , Indicates that there are no properties or methods defined

Add : if Foo Class has inheritance , namely class Foo(Bar):.... Is equivalent to type('Foo',(Bar,),{})


Python— More articles on metaclasses

  1. python The metaclass :type and metaclass

    python The metaclass :type and metaclass python Everything is an object , So a class itself is an object . Class has the ability to create objects , So who creates the class ? The answer is type. 1. use tpye Function to create a class class A(ob ...

  2. Python The metaclass - Metaclasses

    Python The metaclass - Metaclasses By default , classes Yes, there is type() Tectonic . Class in a new namespace Be performed , The name of the class class name binding ( ...

  3. Python How to create your first Python The metaclass ?

    Abstract : Through this paper , It will be discussed in depth Python The metaclass , Its properties , How and when to be in Python Metaclasses are used in . Python Metaclasses set the behavior and rules of a class . Metaclasses help modify instances of classes , And it's quite complicated , yes Python One of the advanced functions of programming . ...

  4. python The metaclass

    Reprinted from  http://blog.jobbole.com/21351/ Class is also an object Before you understand metaclasses , You need to master Python Class in .Python The concept of "class" in Chinese refers to Smalltalk, It's a little strange . At large ...

  5. [python]python The metaclass

    I'm looking at Django frame , Inside filter I don't understand the implementation principle , Finally, it turns out that python Is related to the metaclasses of . original text :http://stackoverflow.com/questions/100003/what ...

  6. Python Metaclass practice -- Define one and collections In the same way namedtuple

    You may be familiar with collections There is a good extended data type in the module -namedtuple. If you don't know this type yet , So look at the standards manual . I use metaclasses to easily define a namedtuple. Put the code on first ...

  7. python Metaclass analysis

    Just beginning to come into contact with Python The concept of metaclass in the new class is very tangled .. I don't know what this is ... Let's use the following definitions to illustrate : (1)Python in , Class is also an object .. It's just that the object is special , It's used to create other ...

  8. python Metaclass understanding 2

    Okay , There are new gains in understanding metaclasses , It's like a decorator , It's just that decorators are decorating functions , Metaclasses are used to customize a class . The code is as follows , This is a metaclass that uses a function to pass to a class : input: def upper_attr(class_nam ...

  9. 3.python Metaclass programming

     1.1.propety Dynamic properties In object oriented programming , We usually map nominal things into attributes , The verb is mapped into the method . stay python They correspond to attributes self.xxx And class methods . But sometimes we need attributes based on ...

Random recommendation

  1. Open source task management platform TaskManager Introduce

    I was going to write a long time ago Quartz Series articles , Now it's finally possible . Starting from this article, I will take you to realize your own task management platform . Do you ever need an app to perform a task at work ? This task every day or every Tuesday night 11:30, Maybe just the last day of every month ...

  2. extjs 4.2 Highly adaptive

    Problem description : gridPanel Put it in tabpanel Page , And this tabpanel Page is through add Method , The overall layout of the page is : First one viewPort Layout ,left Area is a treePanel, By clicking on t ...

  3. 【 turn 】LokiJS: pure JavaScript Implementation of lightweight database

    The original is translated from :http://www.html5cn.org/article-7091-1.html LokiJS A lightweight document oriented database , from JavaScript Realization , Performance is above everything . The purpose is to JavaSc ...

  4. In the web page Javascript Acquisition time

    <script language="javascript"> <!-- function initArray() { for(i=0;i<initArray ...

  5. Jquery easyui datagrid export Excel

    From:http://www.cnblogs.com/weiqt/articles/4022399.html datagrid Extension method of , Used to generate the current data into excel What you need . 1 <sc ...

  6. Spring Integrate Redis The one that appears Timeout Method can not find the problem

    Let's get to the point . Dependency package :jedis 2.9.0. spring-data-reids 1.4.1 Tips :redis.clients.jedis.JedisShardInfo.setTimeout(I) ...

  7. Development servlet Three ways

    The first one is : Realization Servlet Interface ServletDemo class Realization Servlet Interface public class ServletDemo implements Servlet { // Initialize the servlet ...

  8. 《java.util.concurrent Package source code reading 》23 Fork/Join Framework Fork The tip of the iceberg

    The last article goes all the way to ForkJoinWorkerThread Of pushTask Method , There is still no way to explain Fork Principle , So let's take a look ForkJoinWorkerThread Of run Method : public ...

  9. python Study diary ( First knowledge of recursion and algorithm )

    Recursive function Definition Definition of recursion —— Call the function itself in a function The maximum depth of recursion ——997, Stack overflow . Use recursive functions to prevent stack overflow . In the computer , Function call is through stack (stack) This kind of data structure realizes , Every time I enter ...

  10. PowerApp Document

    https://docs.microsoft.com/en-us/powerapps/ PowerApp Document: https://docs.microsoft.com/en-us/powe ...