[Timlinux] Python meta-class

Source: Internet
Author: User

1. Type function
Name ="This is a string"Print(Type (name))#<class ' str ' >Print("*"* 10,"Dividing Line","*"* 10) CLS= Type ('Foo', (), {}) F=CLS ()Print(Type (f))#<class ' __main__. Foo ' >Print(Type (CLS))#<class ' type ' >Print(CLS.__name__)#FooPrint("*"* 10,"Dividing Line","*"* 10)definit (self, Name, age): Self.name=name Self.age= AgePrint(Self.name, self.age) CLS= Type ('Foo', (object,), {'__init__': init}) F= CLS ('Tim', 22)#Tim
View Code

2. __new__ function
classFoo (object):def __init__(self, Name, age): Self.name=name Self.age= AgePrint(Self.name, Self.age)deftmp (self):Print("Call tmp ()")    def __new__(CLS, *args, * *Kwargs):Print("Call __new__") obj= object.__new__(CLS)Print("ID (obj) = = =", id (obj))returnobjf1= Foo ('Tim', 22)#This operation equals the two-step operation below = = =. Print("ID (f1) = = =", ID (F1)) f1.tmp ()#Call __new__#ID (obj) = = = 1507711426120#Tim#ID (f1) = = = 1507711426120#Call tmp ()F2= Foo.__new__(Foo)Print("ID (F2) = = =", ID (F2)) F2.__init__('Tim', 22) f2.tmp ()#Call __new__#ID (obj) = = = 1507711426232#ID (F2) = = = 1507711426232#Tim#Call tmp ()
View Code

3. __init__ function

The __init__ function, if the object is declared by the Foo class, calls the __new__ first, then creates an object by using the Object.__new__ method provided by Python, then returns the object, and then the returned object, which invokes _ _init__ method.

FOO.__NEW__----use this object to invoke the Foo.__init__ method----to complete the object declaration of the class by object.__new__ production object

4. __metaclass__ variables

Ttt

[Timlinux] Python meta-class

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.