(python) __str__ vs __del__

__str__: Change the string display of the object.

class People:
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
    def __str__(self):
        # print('===========>')
        return '<Name: %s Age: %s Gender: %s>' %(self.name,self.age,self.sex)

obj=People('monicx',23,'male')
# print(obj.__str__())#<__main__.People object at 0x0000000001E78AC8>
# print(obj)#等于print(obj.__str__())<__main__.People object at 0x00000000026D8AC8>
#After defining __str__(), it becomes:
print(obj)#<name: monicx age: 23 gender: male>

__the__

Destructor method, when the object is released in memory, it will be automatically destructed and executed.

import time
class People:
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex

    def __del__(self):#It will be triggered automatically when the object is deleted
        print ('__ del__')

obj=People('monicx',23,'male')
time.sleep(2)
 
 

If the object generated by the query is only at the python program level (user-level), then we do not need to define __del__, but if the generated object also initiates a call to the operating system, that is, an object has user-level and kernel-level resources. , you must recycle system resources while clearing the object, and __del__ is used. It is an application scenario related to resources, as follows:

class MyOpen:
    def __init__(self,filepath,mode='r',encoding='utf-8'):
        self.filepath=filepath
        self.mode=mode
        self.encoding=encoding
        self.fobj=open(filepath,mode=mode,encoding=encoding)
    def __str__(self):
        msg='''
        filepath:%s
        mode:%s
        encoding:%s
        '''%(self.filepath,self.mode,self.encoding)
        return msg
    def __del__(self):
        #Recycle system resources first when recycling application resources.
        self.fobj.close()

f=MyOpen('test.py')#f. is a python variable that will be recycled.
print(f.fobj)
res=f.fobj.read()
print(res)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325752215&siteId=291194637