Meta-class Metaclass in Python

Source: Internet
Author: User
Tags class definition

Meta-class Metaclass

A meta-class is a way for you to define how certain classes are created. Fundamentally, gives you control over how to create classes.

A meta-class is also a class, which is a type class.

A meta class is typically used to create classes. When executing a class definition, the interpreter must know the correct meta-class of the class, and if this property is not defined, it will look up the __metaclass__ property in the parent class. If you haven't found it yet, look for global variables.

For traditional classes, their meta-class is types. ClassType.

The Meta class also has a constructor that passes three parameters: the class name, the tuple that inherits the data from the base class, and the Class property dictionary

Let's define a meta class that requires the class to be provided with a __str__ () method and a warning if no __repr__ () method is provided.

The from warnings import warn# meta class needs to inherit the type class Class reqstrsugrepr (type):     def  __init__ (CLS, NAME, BASES, ATTRD):     #构造函数需要传递的参数为类名, base class, Class Property dictionary          super (REQSTRSUGREPR, CLS). __init__ (NAME, BASES, ATTRD         #  determine if the __str__ string is in the class's attribute dictionary          if  ' __str__ '  not in attrd:             raise typeerror (' class requires overriding of __str__ () ')         if  ' __repr__ '  not in attrd:             warn (' Class suggests overriding of  __repr__ () \ n ',  stacklevel=3) Class foo (object):     #给类指定元类       __metaClass__ = reqstrsugrepr    def foo (self):         pass# This piece of code does not need to create a class to test, run directly will be error, visible meta-class skill.

Resources:

http://blog.jobbole.com/67748/

Http://www.cnblogs.com/btchenguang/archive/2012/08/27/2659369.html

http://blog.csdn.net/dysj4099/article/details/18862137

Meta-class Metaclass in Python

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.