Introduction to metadata in python

Source: Internet
Author: User
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

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.