Meta-classes in Python (translated)

Source: Internet
Author: User

Add by Zhj: This is the big stackoverflow on a small white raised the question, OK, I admit that I am also small white, meta-class this piece I also want to understand many times,

But after all, because it is too difficult to understand and defeated the array. Read this article to understand a lot, add the woodpecker community to the Python type and object of this article. Lying trough,

This is a perfect pair, the sun and the sword Ah, the moon. Finally killed the Meta class. There is a change in translation, it is suggested to look together with the original.

Original: Http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python?answertab=votes#tab-top

Class is an object

Before you understand the meta-class, you need to master the classes in Python first. In Python, the definition of a class is special, which draws on the Smalltalk language. In most

In several languages, a class is just a piece of code that describes how to create an object, in Python, to some extent:

class Objectcreator (object): ...        Pass  >>> my_object = objectcreator ()print(my_object)<__main__ . Objectcreator Object at 0x8974f2c>

However, the classes in Python are more than that. Class is also an object, yes, I'm right.

When you use the keyword class, an object is created when the Python interpreter executes. As follows, Python creates an object in memory, and in the symbol table

Add an identifier, Objectcreator, to that object, which is referred to in Python, and we often call it a variable.

class Objectcreator (object): ...        Pass

We call this object a class object, because the object can be instantiated to create an instance object, so we call it a class.

Because it is an object, so:

    • It can be assigned to a variable
    • You can copy it.
    • You can add properties to it
    • It can be used as a function parameter

Like what

>>>Print(Objectcreator)#can print it<class '__main__. Objectcreator'>>>>defEcho (o): ...Print(o) ...>>> Echo (Objectcreator)#class object as a function parameter<class '__main__. Objectcreator'>>>>Print(Hasattr (Objectcreator,'New_attribute')) False>>> Objectcreator.new_attribute ='Foo' #increase the properties of a class>>>Print(Hasattr (Objectcreator,'New_attribute')) True>>>Print(objectcreator.new_attribute) Foo>>> Objectcreatormirror = Objectcreator#assign a value to another variable>>>Print(objectcreatormirror.new_attribute) Foo>>>Print(Objectcreatormirror ())<__main__. Objectcreator Object at 0x8997b4c>


Dynamically creating classes through the Type class

In fact, the class object is also the result of instantiation, that is, the class object is instantiated by another class, we call the class as a meta-class, that is, the meta-class is the class that produces classes, and vice versa,

If Class X is instantiated and gets a class object, then X is the Meta class. In Python, only the type class and its subclasses can be a meta-class. One more word, there will be chicken eggs,

The problem of chicken eggs. In Python, everything is an object, and all objects are the result of class instantiation. Objects are instantiated by the class, and the class is also an object, and it is also made up of classes (meta-classes)

Instantiation gets, continues upward, the meta-class is also an object, also to be instantiated by another meta-class, so there is no end. In Python, this retrospective terminates in the type class.

The meta-class is the type class or its subclass, and the class of type class is its own, haha, the type class to create their own, hell, of course, this feature of the type class is the Python designer

Guido van Rossum and others are designed and implemented. As for how the Python interpreter found the meta-class, we'll talk about it later.

Do you remember the type () method? We often use it to look at the class that an object x belongs to, that is, the class that created the object X, and when Object X is a class object, you see the meta class. As follows

>>>Print(Type (1))<type'int'>>>>Print(Type ("1"))<type'Str'>>>>Print(Type (objectcreator)) class #查看创建 the Objectcreator class<type'type'>>>>Print(Type (Objectcreator ()))<class '__main__. Objectcreator'>

The type class has another feature that creates a class, makes some information about the class as a parameter of type (), and returns a class. I know that type has a different function depending on the input parameters,

This practice is foolish. When type () has only one parameter, its function is to return the class that created the parameter object, and when more than one argument, type () is instantiated for the type class, and the instantiation gets

A class and returns the class. Type when creating a class, the parameter format is as follows, ClassName is the class name, the string type, Parentclasses is the class all parent class, the tuple type, Attrs is all {property: value} of the class,

The dictionary type.

Type (classname, parentclasses, Attrs)

Like what

class Myshinyclass (object): ...        Pass

When the interpreter executes, it goes to the following statement, and of course, you can write it directly.

Myshinyclass = Type ('myshinyclass', (object,), {})

Let's define a class and define properties in the class, such as

class Foo (object): ...        = True

It will be translated into the form below,

>>> foo = type ('Foo', (), {'bar': True})

Let's see.

Print (Foo)<class'__main__. Foo'print(foo.bar) True>>> f = Foo ()print(f) <__main__print(f.bar) True

We can inherit it with another class, so:

>>>   class  foochild (Foo):         ... Pass

would be:

>>> foochild = Type ('foochild', (Foo,), {})print(foochild )<class'__main__. Foochild'print#  Bar is inherited from FooTrue

OK, you will want to add a method to your class. Define a function and assign it to the properties of the class

>>>defEcho_bar (self): ...Print(Self.bar) ...>>> Foochild = Type ('Foochild', (Foo,), {'Echo_bar': Echo_bar})>>> hasattr (Foo,'Echo_bar') False>>> hasattr (Foochild,'Echo_bar') True>>> My_foo =Foochild ()>>>My_foo.echo_bar () True

Speaking of which, you should have understood the process of creating a class. Is it so simple that Python creates classes? Are instantiated directly from the type meta-class?

No, you can specify a meta-class, which is the __metaclass__ property.

What is a meta-class

The meta-class is the class that creates the class (saying that the author speaks wordy enough, of course, for small white, say a few more times to see)

In the above, we mentioned that you can use the type () to view the classes that create an object, or you can use __class__, as follows

>>> age = 35>>>.__class__<type'int'>>>> name ='Bob'>>> name.__class__<type'Str'>>>>defFoo ():Pass>>> foo.__class__<type'function'>>>>classBar (object):Pass>>> B =Bar ()>>> B.__class__<class '__main__. Bar'>

What is that __class__.__class__? __CLASS__ returns a class object, and once again __class__ returns the Meta-class, as follows

, the following conclusion is not universal, some classes of meta-class is not a meta-class. Of course, if you have been calling __class__, after a finite number of times,

It always returns the type class.

>>> age. __class__. __class__ ' type '>>>> name. __class__. __class__ ' type '>>>> foo. __class__. __class__ ' type '>>>> B.__class__. __class__ ' type '>

What is a meta-class

Meta-classes in Python (translated)

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.