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.