python foundation 12 polymorphism / encapsulation / reflection / inheritance wrapper / getattr authorization

  • polymorphic

  • Definition: objects instantiated by different classes call the same method and execute different logic
  • Object oriented classes are called factories to produce instances. Therefore, the factory function str is the function that generates string objects
  • len(str1) is essentially str__ len__ (). That is, different classes can call the same method len
  • Polymorphism is a dynamic binding state when calling methods of different objects. Polymorphic response at execution time
  • Object oriented, that is, don't force yourself to do things and define classes
  • Polymorphism is an embodiment of inheritance. The purpose of inheritance is to realize the reuse of code, and polymorphism makes this reuse goal manifest
  • encapsulation

  • It's a characteristic, an idea, not a specific technology
  • Encapsulation provides an interface. Encapsulation means hiding
  • _author_='xiansuo '
    
    class People:
        _star='earth'#Starting with a single underscore is hidden and should not be used externally
        __star='earth'#python Renamed it,_People__star
        
        def get_star(self):#An access function, or interface function, provides an interface for external users to access hidden properties
            print(self._star)
  • Three layers of encapsulation
  1. Class is sack, which itself is a kind of encapsulation
  2. Private is defined in the class. It is only used inside the class and cannot be accessed outside. But it's just a convention. python doesn't actually restrict access
  3. Clearly distinguish the internal and external implementation logic, which is unknown to the outside, and provide an access interface for the logic encapsulated to the inside for external use
  • Advantages of object oriented
  1. You don't need to know the logic of God's creation by encapsulating the inside and outside. You can know what God wants you to know and clarify the hierarchy
  2. Inheritance + polymorphism supports normalization design at the language level, that is, everything is an object and can be called according to a unified format
  • Generalization: all subclasses and superclasses have the same characteristics. Specialization: describe the difference between subclass and parent
  • Reflection / introspection

  • class BlackMedium:
        feture='Ugly'
        def __init__(self,name,addr):
            self.name=name
            self.addr=addr
    
        def sell_house(self):
            print('[%s]I'm selling my house. I'm a fool to buy it'%self.name)
    
        def rent_hourse(self):
            print('[%s]I'm renting a house. Fools rent it'%self.name)
    
    
    b1=BlackMedium('Wancheng land','Tianlu Garden')#Generate instance
    
    print(hasattr(b1,'name'))#Detection example b1 Can I call name Data properties for
    
    print(getattr(b1,'name'))#Get instance b1 Medium name Attribute value
    func=getattr(b1,'rent_hourse')#Get instance b1 The address of the function in, equivalent to b1.rent_hourse
    func()#Execute the above functions
    print(getattr(b1,'rent_hoursesdfsdaf','There is no such attribute'))#If no match is found, the following value is returned
    
    setattr(b1,'sb',True)#Give examples b1 Add a value to your dictionary, key and value
    print(b1.__dict__)
    setattr(b1,'name','SB')
    setattr(b1,'func',lambda x:x+1)#You can add function attributes to instances
    print(b1.__dict__)
    print(b1.func(10))
    
    delattr(b1,'sb')
    print(b1.__dict__)

     

  • Reflection is to find yourself. Application scenario: it is applicable to team cooperation, division of labor, one person's vacation, and does not affect other people's code work. Pluggable program.
  • Dynamic import module

  • The bottom layer of dynamic import is based on reflection
  • Everything is an object, and modules are objects
  • m=__import__('dic')#Import the module as a string. whether dic.How many floors, m Only get dic
    print(m)
    
    m.t.test()#implement m Below t Modular test function
    
    #m1.t in_test2()Function, in this case*Cannot be imported.
    from m1.t import *
    from m1.t import test1,_test2#In this way, you can import
    test1()
    test2()
    
    #import importlib
    m=importlib.import_module('m1.t')
    print(m)
    m.test1()#The above content is also imported in the form of string
  • Class

  • A class is essentially an object, and the above reflection method is also applicable to a class
  • attr method starting with double underscore
  • class Foo:
        x=1
        def __init__(self,y):
            self.y=y
        
        
        #The following three methods are built-in in the system. If they are not defined by the user, the built-in methods in the system will be triggered under appropriate conditions
        def __getattr__(self, item):
            print('implement_getattr_')
        #__getattr__yes python If the built-in method for a class is not defined by the user, the default is to report an error.
        #If it is user-defined, no error will be reported and the user-defined function will be executed
        
        #The following two operations are more than one, and the system defaults__delattr and__setattr_That's what you're doing
        def __delattr__(self, item):
            print('Delete operation_delattr_')
            #del self.item#Infinite recursion
            self.__dict__pop(item):#Delete the underlying dictionary
    
        def __setattr__(self, key, value):#If judgment can be added to realize the re setting if certain conditions are met
            print('_setatter_implement')
            # self.key=value#This operation is a setting operation and will be triggered_ setattr_ Operation, falling into recursion
            self.__dict__[key]=value#Operate the underlying dictionary to set
    
    f1=Foo(10)
    print(f1.y)
    print(getattr(f1,'y'))
    
    f1.ssssss#call f1 If there are no properties, execute getattr function
    del f1.y#Triggered when a delete operation occurs__delattr_operation
  • Inheritance and further processing

  • Secondary processing standard type
  • str, list and tuple are all classes
  • class List(list), which inherits the list class
  • class List(list):
        def append(self, p_object):
            if type(p_object) is str:
                # self.append(p_object)    #Such a call falls into the recursive trap again
                # list.append(self,p_object) #Call the of the parent class append itself. It is recommended to use the super method
                super().append(p_object)
            else:
                print('Only string types can be added')
    
        def show_midlle(self):  # Inherit the class of the list and further process to obtain the median value of the string
            mid_index = int(len(self) / 2)
            return self[mid_index]
    
    
    l1 = List('helloworld')
    # print(l1.show_midlle())
    l1.append('SB')
    print(l1)
    l1.append(1212)
  • The combination method completes authorization, and the effect is equivalent to inheritance processing

  • Authorization: authorization is a feature of packaging. Packaging a type is usually some customization of existing types. This method can create, modify or delete the functions of the original product. Others remain the same. The process of authorization, that is, all updated functions are handled by a part of the new class, but the existing functions are authorized to the default properties of the object. The key to authorization is coverage__ getattr__ method
  • Steps for authorization
  1. Customize your own types based on standard types
  2. It has nothing to do with inheritance. It is implemented through getattr
  • class FileHandle:#Add a new method on the built-in file of the system, and authorize the rest to the built-in file object of the system getattr Implements inherited operations
        def __init__(self,filename,mode='r',encoding='utf-8'):
            # self.filename=filename
            self.file=open(filename,mode,encoding=encoding)#System provided
            self.mode=mode
            self.encoding=encoding
    
        def __getattr__(self, item):
            # self.file.read
            return getattr(self.file,item)#Return to system item method
    
    f1=FileHandle('a.txt','w+')
    print(f1.__dict__)
    print('==>',f1.read)#trigger__getattr__

Added by Weiry on Wed, 19 Jan 2022 13:02:13 +0200