Meta-class programming--Metaclass

Source: Internet
Author: User

#Class is also an object, type the class that creates the classdefCreate_class (name):ifName = ="User":        classUser:def __str__(self):return "User"        returnUserelifName = =" Company":        classCompany :def __str__(self):return " Company"        return Company#type dynamic Creation class#user = Type ("User", (), {}) #名称, inherit (base class to inherit), property or method (but in dictionary form)defSay (self):return "I am user"    #return Self.nameclassBaseClass ():defAnswer (self):return "I am baseclass"classMetaclass (type):#inherit type as meta class    def __new__(CLS, *args, * *Kwargs):returnSuper ().__new__(CLS, *args, * *Kwargs) fromCollections.abcImport*#What is a meta-class, which is a class object that creates a class <-class (object) <-typeclassUser (metaclass=metaclass):def __init__(self, name): Self.name=namedef __str__(self):return "User"#The instantiation process of a class in Python will first look for Metaclass and create the user class by Metaclass#type to create the class object, instanceif __name__=="__main__":    #MyClass = Create_class ("user")    #my_obj = MyClass ()    #print (Type (my_obj))    #user = Type ("User", (BaseClass,), {"Name": "User", "Say": Say})My_obj = User (name="Bobby")    Print(my_obj)

Meta-class programming--Metaclass

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.