Python classes and objects-extensions

Source: Internet
Author: User

1. Dynamically creating properties or methods for a class or object

2, __slots__ = (' name ', ' age '), "instance" can only create a specified property property or method---modern class

3. Different constructors for executing the parent class
Father.__init__ (self)--classic class
Super (Son,self). __init__ ()--New class

4. PERSON.__BASES__ displays only one layer of inherited all parent classes
5, __call__
__call__ an already instantiated object P, in the call P ()
6. Everything in Python is an object, and the class itself is an object, and the class is generated by type.

Class Foo
Pass
Bar = Type (' Bar ', (object,), {' name ': 123, ' Func ': Hello})

The above equals

class Bar:     ' YANGMV '    def func (self):         Print ' go func '  = Bar (). Func ()


In this case, for a defined class, once a class is defined, the constructor of the type class is called once, and how is it validated?

7. __metaclass__ can specify that the class is generated by that type

class metaclass (type):     def __init__ (self,name,bases,dicts):         Print name      class C1:     __metaclass__ = metaclass     class  C2:    __metaclass__ = Metaclass

8, __init__ __new__ __call__
We know that executing F = Foo () will execute the constructor by default __init__
Actually executed: type (' foo ', bases,dicts). __call__ (' foo ')

classmetaclass (type):def __init__(self,name,bases,dicts):Printnamedef __call__(Self, *args, * *Kwargs):PrintSelf result= self.__new__(Self, *args, * *Kwargs)Printresult type (result).__init__(result,*args,**Kwargs)returnresultclassC1:__metaclass__=Metaclassdef __init__(self):Print 'c1.__init__'Self.name=' YANGMV'             def __new__(CLS, *args, * *Kwargs):PrintCLSPrintargsPrintKwargsreturnObject.__new__(CLS, *args, * *Kwargs)defHello (self):Print 'Hello'classC2:__metaclass__=Metaclass#C = C1 ()C1 = object.__new__(C1) C1. Hello ()

Python classes and objects-extensions

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.