Article directory
This article is still the object-oriented content, mainly analyzes the following three methods of object-oriented programming: encapsulation, reflection, dynamic import module, class built-in attr attribute, packaging and authorization
encapsulation
The essence of encapsulation:
Putting methods in classes and classes in modules is called loading;
In other places, when importing modules, referencing classes, and calling methods, you can't see the specific logic of the corresponding modules, classes, and methods. You only need to know the name, because they are hidden. This is called sealing
The essence of encapsulation is to distinguish the inside and the outside clearly, so encapsulation is a kind of thought, the inside is the inside, the outside is the outside
class People: #Variables that start with "U" are hidden variables that cannot be seen when they are used externally _place= 'Beijing' __position= 'Python' def __init__(self,id_num,name,age,salary): self.id_num= id_num self.name= name self.age= age self.salary= salary def get_id(self): print('I am a privacy,I need to find id [%s]' %self.id_num) #instantiation v1= People('12345678','Zoro',22,2000000) print(v1._place) #Although it is hidden, it can still be called. Hiding is just a convention, but python does not really restrict your access #But at the beginning, you must bring the class name #print(v1.__position) print(v1._People__position
Operation result:
Encapsulation in real effect: clearly distinguish the internal and external implementation logic, which cannot be known by the external, and provide an access interface for the logic encapsulated into the internal to be used by the external
reflex
The nature of reflection:
Also known as program introspection, it mainly refers to the ability of a program to access, detect and modify its own state
class BadGuy: feature= 'Ugly' #Characterized by ugliness def __init__(self,name,address): #Two parameters, one name and one address self.name = name self.address= address #Actions (function properties) def sell_house(self): print('[%s] Selling house'%self.name) def rent_house(self): print('[%s] Renting a house' %self.name) #instantiation p1= BadGuy('Black intermediary','Shahe') #p1.sell_hourse() #Start self reflection print(hasattr(p1,'name')) #Whether there is the attribute name in the object, and the return value is Boolean print(hasattr(p1,'sell_house')) #The first parameter of the hasattr() reflection function is an object and the second is a string, which is equivalent to p1.name print(getattr(p1,'name')) #Return the value corresponding to the property name (the function property returns the function memory address), #The first parameter is an object and the second parameter is a string. If it does not exist, an error will be reported print(getattr(p1,'rent_house')) #The third parameter is Default, indicating that if it does not exist, the third parameter will be output print(getattr(p1,'r_house','The property does not exist')) setattr(p1,'The fifth emperor of the new world','Monkey D Luffy') #Add a key value pair in the attribute dictionary, that is, one more attribute print(p1.__dict__) #You can also add function properties setattr(p1,'add_num',lambda x:x+1) #Anonymous function of self increasing 1 setattr(p1,'join_str',lambda self:self.name+'yes BadGuy') #The anonymous function of concatenated string print(p1.add_num(1313)) #Calling function print(p1.join_str(p1)) #Because it is an anonymous function with self, the parameter passed in is the object name delattr(p1,'The fifth emperor of the new world') #Delete the key value pairs in the attribute dictionary. The first parameter is the object name and the second parameter is the key print(p1.__dict__)
Operation result:
Dynamic import module
First, customize a simple module and put it into the web folder to form a package:
#from web import test #Import the test custom module in the web package normally #Dynamic import module module = __import__('web.test') #Import the test module in the web package under the relative path print(module) #In fact, only the web package is imported. The whole module represents the web without test1 #In this way, you can import test1 under the web module.test.test1() #Import and call test1 function #Using the importlib module to import import importlib m = importlib.import_module('web.test') print(m) #Different from the module, the imported module is test #So it can be called directly m.test2() #m.test.test2 is not needed
Operation result:
Class built in attr attribute
There are three types of built-in attr attributes:
getattr
setattr
delattr
class Test: y = 2020 def __init__(self,x): self.x= x def __getattr__(self,item): #item is a required parameter print('Being implemented__getattr__Method') def __delattr__(self,item): print('Triggering__delattr__operation') def __setattr__(self,key,value): #When setting the value, it is added to the property dictionary, so the key value pair is passed in print('In use__setattr__Set value') #__Set value operation is required in setattr \ self.__dict__[key]= value #Set the original property dictionary #instantiation p1= Test(520) #__getattr Uuuuuu method print(p1.x) #Using the property dictionary to get properties print(getattr(p1,'__getattr__')) #Using the getattr function to get properties p1.jjjjjjjjjjjjjjjjjj #A nonexistent property name will trigger the execution of the getattr method #__delatrr method del p1.y #When del operation is executed, the execution of the "delattr" method will be triggered #p1.__dict__.pop('x') #This method does not trigger the execution of the #__setattr? Method, when the set value of life will be triggered print(p1.__dict__) #Output original attribute dictionary p1.y= 13 #If you set two new key value pairs, you will execute Zu setattr twice__ p1.z= 14 print(p1.__dict__)
Operation result:
__The benefits of getattr \
When an attribute that does not exist is passed in, an error will not be reported, but a corresponding reminder will be output
class Test: y = 2020 def __init__(self,x): self.x= x def __getattr__(self,item): #item is a required parameter print('Properties you are looking for[%s]Non-existent!' %item) #The item at this time is the property passed in when calling #instantiation p1= Test(520) #__getattr Uuuuuu method print(p1.x) #Using the property dictionary to get properties print(getattr(p1,'__getattr__')) #Using the getattr function to get properties p1.jjjjjjjjjjjjjjjjjj #A nonexistent property name will trigger the execution of the getattr method
Operation result:
Packaging and authorization
Packaging: one type of packaging is usually used to customize the existing types. You can create, modify and delete the functions of the original products, and the others remain the same
Authorization: authorization is a feature of packaging. All updated functions are handled by some part of the new class, but the existing functions are authorized to the default properties of the object. The key point to implement authorization is to override the getattr method
import time #Import time module class Open: #A class that produces a file def __init__(self,filename,mode,encoding): #self.filename= filename #Open a file and set it to the self.file property self.file= open(filename,mode,encoding=encoding) self.mode= mode self.encoding= encoding #A transfer station def __getattr__(self,item): print('[%s]Non-existent!' %item) print(item,type(item)) #Output the incoming value and its type #Implementation of authorization return getattr(self.file, item) #Get the information in self.file. If it does not exist, a new one will be created and the memory address of the new method will be returned #Overriding the getattr method, that is, customizing a write method, means that a write method already exists, #So it will not trigger the getattr method to create a new write method def write(self,line): #The second parameter is the content of the incoming write t = time.strftime('%Y-%m-%d %t') #Character format display system time, year month day self.file.write(t + line) #String splicing #Instantiation and call p1= Open('a.txt','r+','gbk') print(p1.file) #Output file information p1.read #Trigger the getattr, run the getattr() method #After creating an item method, you can call the print(p1.write) #Trigger getattr again to create a new write method #You can write p1.write('Is ok...\n') p1.write('Finally, it can be written in\n') p1.file.close() #Close files to update data
Operation result:
The contents are also written in the file normally: