Python learning reflection and built-in methods

1. Reflection

Python is a dynamic language, and the reflection mechanism is regarded as the key to a dynamic language.

The reflection mechanism refers to the running state of the program

For any class, you can know all the properties and methods of this class;

For any object, you can call any of its methods and properties.

This function of dynamically obtaining program information and dynamically calling objects is called a reflection mechanism.

 Implementing reflection in Python is very simple. During the running of the program, if we get an object that does not know what attributes are stored, if we want to manipulate its internal attributes, we can first get the attributes of any class or object through the built-in function dir List, the list is all in string format.

>>> class People: 
... def __init __ (self, name, age, gender): 
... self.name = 
name ... self.age = age 
... self.gender = gender 
... 
>> > obj = People ('egon', 18, 'male') 
>>> dir (obj) # The attributes viewed in the list are all strings 
[..., 'age', 'gender', ' name ']

The next step is to find a way to manipulate the attributes of objects through strings, which involves the use of built-in functions hasattr, getattr, setattr, delattr (everything in Python is an object, and classes and objects can be manipulated by these four functions The usage is the same.

class Teacher:
     DEF  the __init__ (Self, FULL_NAME): 
        self.full_name = FULL_NAME 

T = Teacher ( ' Egon Lin ' ) 

# the hasattr (Object, 'name') 
the hasattr (T, ' FULL_NAME ' ) # Press string 'full_name' Analyzing There is no attribute t.full_name 

# getattr (object, 'name', default = None) 
getattr (t, ' full_name ' , None) # Equivalent to t.full_name, if there is no such attribute, return the default value None 

# setattr (x, 'y', v) 
setattr (t, ' age ' ,18) #= 18 is equivalent to t.age 

# delattr (X, 'Y') 
delattr (T, ' Age ' ) # is equivalent to del t.age

Based on reflection, you can manipulate the properties of objects very flexibly, such as reflecting the results of user interaction to specific function execution.

>>> class FtpServer: 
... def serve_forever (self): 
... while True: 
... inp = input ('input your cmd >>:') .strip () 
... cmd, file = inp. split () 
... if hasattr (self, cmd): # According to the cmd input by the user, determine whether the object self has the corresponding method attribute 
... func = getattr (self, cmd) # According to the string cmd, get the object self corresponding method attribute 
... FUNC (File) 
... DEF GET (Self, File): 
... Print ( '% S Downloading ...' File%) 
... DEF PUT (Self, File): 
. .. print ('Uploading% s ...'% file) 
... 
>>> server = FtpServer () 
>>> server.serve_forever () 
input your cmd >>: get a.txt 
Downloading a.txt .. .
input your cmd>>: put a.txt
Uploading a.txt...

 

2. Built-in methods

There are many special methods built into Python's Class mechanism to help users highly customize their own classes. These built-in methods start and end with double underscores and will automatically trigger when certain conditions are met. And __del__ as an example to briefly introduce their use.

The __str__ method is automatically triggered when the object is printed. The print function prints its return value. We usually customize the object's printing information based on the method. This method must return the string type.

>>> class People: 
... def __init __ (self, name, age): 
... self.name = 
name ... self.age = age 
... def __str __ (self): 
... return '< Name:% s Age:% s> '% (self.name, self.age) #The return type must be a string 
... 
>>> p = People (' lili ', 18) 
>>> print (p) #Trigger p .__ str __ (), print after getting the return value 
<Name: lili Age: 18>

__del__ will be triggered automatically when the object is deleted. Because Python's built-in garbage collection mechanism automatically cleans up Python program resources, when an object only occupies application-level resources, there is no need to customize the __del__ method for the object, but it involves the application system when generating an object. In the case of resources (such as files opened by the system, network connections, etc.), regarding the collection of system resources, Python's garbage collection mechanism will not come in handy. We need to customize this method for objects, which is used to automatically Trigger the recovery of system resources.

class the MySQL:
     DEF  the __init__ (Self, IP, Port): 
        self.conn = Connect (IP, Port) # pseudo code, initiates a network connection, system resources required 
    DEF  the __del__ (Self): 
        self.conn.close () # Close network connection recovery system resources 

obj = the MySQL ( ' 127.0.0.1 ' , 3306) # when the object obj is deleted, automatically triggered obj .__ del __ ()

 

Guess you like

Origin www.cnblogs.com/imark7/p/12707660.html