MetaClass allows you to define how some classes are created. Fundamentally, it gives you control over how to create a class. A metadatabase is also a type class. Meta-classes are generally used to create classes. When executing the class definition, the interpreter must know the correct metaclass of the class. If this property is not defined, it will look up the _ metaclass _ attribute in the parent class. If no global variable is found, search for the global variable.
For traditional classes, their meta classes are types. ClassType. The metadatabase also has a constructor that transmits three parameters: class name, The tuples that inherit data from the base class, and the class attribute dictionary. We will define a metadatabase, when writing a class, you must provide a _ str _ () method for the class. If the _ repr _ () method is not provided, a warning is given to you.
FromWarnings
ImportWarn
# The metadata class must inherit the type class
ClassReqStrSugRepr (
Type):
Def
_ Init __(Cls, name, bases, attrd ):
# The parameters to be passed by the constructor are class name, base class, and Class Attribute dictionary.
Super (ReqStrSugRepr, cls ).
_ Init __(Name, bases, attrd)
# Determine whether the _ str _ string is in the attribute Dictionary of the class.
If'_ Str __'
Not
InAttrd:
Raise
TypeError('Class requires overriding of _ str __()')
If'_ Repr __'Not InAttrd:
Warn ('class suggests overriding of _ repr _ () \ n', stacklevel = 3)
ClassFoo (object ):
# Specify a metaclass for the class
_ Metaclass _ = ReqStrSugRepr
DefFoo (Self):
Pass
# You do not need to create a class to test this code. If you run the Code directly, an error is reported, showing the skill of the Meta class. Publish by note