09-06 reflection and built-in method

One reflection

In Python, reflection refers to manipulating the properties of an object through a string, involving the use of four built-in functions (all objects in Python, classes and objects can use the following four methods)

class Teacher:
    def __init__(self,full_name):
        self.full_name =full_name

t=Teacher('Egon Lin')

# hasattr(object,'name')
hasattr(t,'full_name') # Judge whether there is attribute t.full'name by string 'full'name'

# getattr(object, 'name', default=None)
getattr(t,'full_name',None) # Equivalent to t.full_name. If the attribute does not exist, the default value of None will be returned

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

# delattr(x, 'y')
delattr(t,'age') # Equivalent to del t.age

Illustration: spoof 43

Based on reflection, the properties of objects can be manipulated 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 entered by the user, judge whether the object self has the corresponding method attribute
...                 func=getattr(self,cmd) # According to the string cmd, get the method property corresponding to the object self
...                 func(file)
...     def get(self,file):
...         print('Downloading %s...' %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...

Illustration: hoax 44

2. Built in method

Python's Class mechanism has built-in many special methods to help users highly customize their own classes. These built-in methods start and end with double underscores, and will trigger automatically when certain conditions are met. We take the commonly used \\\\\\\\\\.

Illustration: spoof 46

__str_uuuumethod will automatically trigger when the object is printed. What the print function prints is its return value. We usually customize the printing information of the object based on the method, which 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) #Return type must be string
... 
>>> p=People('lili',18)
>>> print(p) #Trigger P. "STR" () and print after getting the return value
<Name:lili Age:18>

__Del? Is triggered automatically when the object is deleted. Because Python's own garbage collection mechanism will automatically clean up Python program resources, when an object only occupies application level resources, it is not necessary to customize the "del" method for the object at all, but when generating an object involves the application of system resources (such as system open files, network connections, etc.), the system resource recovery, python garbage Garbage collection mechanism is useless. We need to customize this method for the object to automatically trigger the operation of recycling system resources when the object is deleted

class MySQL:
    def __init__(self,ip,port):
        self.conn=connect(ip,port) # Pseudo code, initiate network connection, need to occupy system resources
    def __del__(self):
        self.conn.close() # Close network connection and recycle system resources

obj=MySQL('127.0.0.1',3306) # When the object obj is deleted, obj. Del is automatically triggered

Illustration: spoof 45

Tags: Python Attribute network MySQL

Posted on Sat, 18 Jan 2020 09:49:04 -0500 by littlehelp