Python\ Object-oriented advanced

Source: Internet
Author: User

I.__slots__

1.__SLOTS__ concept: is a variable, the value of a variable can be a list, a tuple, or an iterative object, or it can be a string.

2. Access to a property using a point the essence is to access the __dict__ property Dictionary of the class or object (the dictionary of the class is shared, and each instance is independent)

3. Why use: Save memory and not generate new namespaces.

Once the __slots__ is defined, __SLOTS__ uses a more compact internal representation for the instance. The instance is constructed from a small fixed-size array, rather than a dictionary defined by each instance, and the property names listed in __slots__ are internally mapped to the specified small label on the array. A bad place to use __slots__ is that we can no longer add new properties to the instance, only those that are defined in the __slots__.

4. Note: Many of the features of __slots__ depend on common dictionary-based implementations. In addition, classes that define __SLOTS__ no longer support some common class features, such as multiple inheritance.

5. Application scenario: A class produces n multiple objects, the properties of the resulting object are the same, and the properties are managed uniformly using __slots__

class people: __slots__=["x", "Y", "Z"]p=people () print (people.__dict__) > >{' __module__ ': ' __main__ ', ' __slots__ ': [' x ', ' y ', ' z '], ' x ': <member ' x ' of ' people ' objects>, ' y ': <member ' Y ' of ' people ' objects> ' z ': <member ' z ' of ' People ' objects>, ' __doc__ ': None}p.x=1p.y=5p.z=4print (p.x,p.y,p. Z) >>1 5 4p.d=9 #报错 File "c:/python_fullstack_s4/day32/__slots__ method. Py", line +, in <module> p.d=9attribut Eerror: ' People ' object has no attribute ' d ' class Foo: __slots__=[' name ', ' Age ']f1=foo () f1.name= ' Alex ' F1.age=18print (F1 . __slots__) F2=foo () f2.name= ' Egon ' F2.age=19print (f2.__slots__) >>[' name ', ' age ' [' name ', ' age ']# F1 and F2 have no attribute dictionary, unified __slots__ tube, save memory Print (f1.__dict__) #报错 >>traceback (most recent call last): File "C:/python_ Fullstack_s4/day32/__slots__ method. py ", line all, in <module> print (f1.__dict__) attributeerror: ' Foo ' object with no at Tribute ' __dict__ ' 

Two. __iter__ __next__

An iterative object is a method __iter__ ()

Iterators are available in a method __next__ ()

Thus, it is possible to build a class on its own so that its object is both an iterative object and an iterator

From collections Import iterable,iterator# Import module Check if hi can iterate over objects or iterators class Foo:    def __init__ (self,start):        Self.start=start    def __iter__ (self):        return self    def __next__ (self):        if self.start>10: #设置数据限制, When Self.start>10, stop running            raise stopiteration        n=self.start        self.start+=1        return Nf=foo (0) # Print ( Isinstance (f,iterable)) for I in F:print (i) >>012345678910

Three. __doc__

__doc__ is a descriptive message for a class

This property cannot be inherited to subclasses

four.

__MODULE__ represents the object of the current operation in that module

__CLASS__ represents the class of the object that is currently being manipulated

Class Bar ():    Passb=bar () print (b.__class__) print (b.__module__) >><class ' __main__. Bar ' >__main__

Five. __del__

destructor, which automatically triggers execution when the object is freed in memory

Class Open:    def __init__ (self,filepath,mode= "R", encode= "UTF8"):        Self.f=open (filepath,mode=mode,encoding= Encode)    def write:        pass    def __del__ (self): #产生的对象被垃圾处理时        # will trigger __del__        print ("--->del")        self.f.close () f=open ("A.txt", "W") del F # If manually deleted, fired directly, then executed by another program

Six. __enter__ __exit__

The context management protocol, the WITH statement, must declare the __enter__ and __exit__ methods in the class of this object in order for an object to be compatible with the WITH statement

Use:

  1. The purpose of using the WITH statement is to place the block of code in with, and with the end, the cleanup work is done automatically without manual intervention
  2. In a programming environment where you need to manage some resources such as files, network connections, and locks, you can customize the mechanism for releasing resources automatically in __exit__
    Class Open:    def __init__ (self,name):        self.name=name    def __enter__ (self):        print (' Appear with statement, object's __ Enter__ is triggered, a return value is assigned to the variable ' declared as ')        # return self    def __exit__ (self, exc_type, Exc_val, EXC_TB):        print (' Execute me when the block execution is complete with Open (' A.txt ') as F:print (' =====> code block ') >> A with statement appears, the object's __enter__ is triggered, The variable with the return value assigned to the as declaration =====> execution code block with the code block executed when execution is done.
      
  3. Throw exception

    with The code block in the statement has an exception, the with after the code is not executed

    Class Foo:    def __enter__ (self):        print ("enter")        return 11111    def __exit__ (self, exc_type, exc_val, exc _TB): Print ("        exit")        print ("Exc_type", Exc_type) #异常类型        print ("Exc_val", Exc_val) #异常值        print ("Exc_tb ", EXC_TB) #追溯信息with Foo (): #1. With Add object () to trigger Enter to run    print (" 1111 ") #2. Print    raise Nameerror () #只要抛出异常, the child code block is finished running                    #触发exit的运行    Print ("******************") #不会运行print ("999999999999999999999999") #子代码运行结束后 (no exception)                            # Normal operation >>enter1111exitexc_type <class ' nameerror ' >exc_val exc_tb <traceback object at 0x02EE1DA0> Traceback (most recent):  File "c:/python_fullstack_s4/day32/Context Management protocol. Py", line +, in <module>    raise Nameerror () #只要抛出异常, the child code block is finished running Nameerror

      

    Exception resolution if the __exit () return value is true, then the exception will be emptied, as if nothing had happened, and the statement with the following normal execution class Open:    def __init__ (self,name):        self.name= Name    def __enter__ (self):        print (' A With statement appears, the object's __enter__ is triggered, a return value is assigned to the variable ' as declared ')    def __exit__ (self, exc_ Type, Exc_val, EXC_TB):        print ("Execute me when the code block executes")        print (exc_type) print (exc_val) print (        exc_tb)        return TrueWith Open (' a.txt ') as F:    print (' =====> code block ')    raise Attributeerror (' * * * * fire, Fire, fight) # Pass to Exc_valprint (' 0 ' *100) #-------------------------------> Execute >> The WITH statement appears, the object's __enter__ is triggered, and the return value is assigned to the variable declared by the AS =====> executing code block with when the code block execution is complete I'm <class ' Attributeerror ' >*** on fire, Fire! ***<traceback Object at 0x02c51e68> 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Seven. __call__

object is appended with parentheses to trigger execution

The execution of the construction method is triggered by the creation object, that is, the object = Class name ();

The execution of the __call__ method is triggered by parentheses after the object, that is, the object () or Class () ()

Class people:    def __init__ (self,name):        self.name=name    def __call__ (self, *args, **kwargs):        print (" Call ") P=people (" Karina ") p () #实例也变成一个可调用对象 >>call

Eight. Meta-class

The meta class is the class class and is the template for the class

A meta-class is used to control how a class is created, just as a class is a template that creates objects

An instance of a meta-class is a class, just as an instance of a class is an object (Foo is a class of type, and the F1 object is an instance of Foo)

Type is an inner Jianyuan class of python that is used to directly control the generated class, and any class defined in Python is actually an object instantiated by the type class.

Methods for generating classes

1.class Foo:    def func:        print ("from Func") F1=foo () F1.func () >>from func

  

2. Format class name =type (class_name,class_bases (parent Class), Class_dict ({})) def func (self): the    print ("from Func") X=1foo=type ("Foo", ( Object,), Dict ({})) print (foo) print (Type (foo)) print (foo.__dict__) >><class ' __main__. Foo ' ><class ' type ' >{' __module__ ': ' __main__ ', ' __dict__ ': <attribute ' __dict__ ' of ' Foo ' objects>, ' __ weakref__ ': <attribute ' __weakref__ ' of ' Foo ' objects>, ' __doc__ ': None}

 

procedure for creating a new object

First, the class wants to generate the object, and the class itself needs to be callable

For the base class, the class is the object of the basic class, that is, in the base class, there needs to be a __call__ () function, which is executed before the __init__ of the class.

In the __call__ () method of the base class, you need to use self.__new__ (self) to create an empty object, which is the class

Once you have a class, you can call the original method __init__ (), in which you are familiar with the generated object.

and return to this class at the end.

 

 

Class Mymetaclass (Type):    def __call__ (self, *args, **kwargs):        obj = self.__new__ (self)        self.__init__ (obj , *args, **kwargs)  # obj.name= ' Egon '        return obj class people (Metaclass=mymetaclass):    def __init__ (self, Name):        self.name = Name WHC = People (' WHC ') print (whc.name)

  

Python\ Object-oriented advanced

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.