Home  >  Article  >  Backend Development  >  Explanation on the usage of python destructor and constructor

Explanation on the usage of python destructor and constructor

巴扎黑
巴扎黑Original
2017-07-17 16:10:142864browse
class Test(object):
    def __init__(self, name):
        self.name = name
        print('这是构造函数')

    def say_hi(self):
        print('hell, %s' % self.name)

    def __del__(self):
        print('这是析构函数')

obj = Test('bigberg')

obj.say_hi()

del obj

#输出
  这是构造函数


  hello bigberg


  这是析构函数

 

Constructor

Used to initialize the content state of the class, the constructor type __init__() provided by Python, That is, this function will be executed when the class is instantiated. The __init__() method is optional. If not provided, Python will give the default __init__ method.

Destructor

"__del__" is a destructor. When del is used to delete an object, its own destructor will be called. In addition, when the object After being called in a certain scope, the destructor will be called once when jumping out of its scope, which can be used to release memory space.

__del__() is also optional. If not provided, Python will provide a default destructor in the background

If you want to explicitly call the destructor, you can use the del keyword: del obj
Garbage collection mechanism 
s = '123'
print('del...running')
del s

When we use del to delete an object, the memory space of the object is not directly cleared. Python uses a 'reference counting' algorithm to handle recycling, that is: when an object is no longer referenced by other objects within its scope, Python automatically clears the object.

The destructor __del__() will automatically clear the memory space of the deleted object when it is referenced.

Constructor:

Used to initialize the content state of the class, the constructor type provided by Python is __init__();

That is, this function will be executed when the class is instantiated. Then we can put the properties to be initialized first into this function. The following program:

Explanation on the usage of python destructor and constructor

__init__() method is optional. If not provided, Python will give the default __init__ method

General data Get the get and set methods that need to be defined


The above is the detailed content of Explanation on the usage of python destructor and constructor. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn