Examples of meta-class usages in Python _python

Source: Internet
Author: User

This article is an example of Python in the use of Meta class, share for everyone to reference. The specific methods are analyzed as follows:

1. The Metaclass is the class used to create the class

2.type (object): Returns the type of an object, the same value as Object.__class__ , type (name,bases,dict): Creates a new type, name is the name of the new class, Value is stored in the __name__ property, bases is the tuple type, the value is saved to the __bases__, and the Dict value is saved in the __dict__

Copy Code code as follows:
Class X:
.. A = 1
...
x = Type (' x ', (object,), Dict (a=1)

3. The class defaults to be created with type (), specifying the Metaclass parameter or inheriting from a class when the class is defined, and the class specifies the Metaclass parameter to customize the creation process of the class

Copy Code code as follows:
Class Orderedclass (Type):
#该方法返回值就是__new__的namespace参数, if there is no namespace value for this method is Dict ()
@classmethod
def __prepare__ (METACLS, name, bases, **kwds):
Return collections. Ordereddict ()
#namespace就是class的__dict__, the object of this dict type has been populated with the corresponding value
Def __new__ (CLS, name, bases, namespace, **kwds):
result = type.__new__ (CLS, name, bases, Dict (namespace))
Result.members = Tuple (namespace)
return result

Class A (Metaclass=orderedclass):
def one (self): Pass
def two (self): Pass
Def three (self): Pass
Def four (self): Pass
Print (a.members)
# (' __module__ ', ' __qualname__ ', ' one ', ' two ', ' three ', ' four ')

I hope this article will help you with your Python programming.

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.