Check the behavior of destructor in Python

Sample code * class_test.py *

class_test.py


class SampleClass:
    num = 0
    def __init__(self, number=1):
        SampleClass.num +=1 #Increment the class variable num by 1 each time an instance is created
        self.num = number #Store the argument number received from the generator at the time of instance creation in the instance variable num.
    def __del__(self):
        SampleClass.num -=1 #Decrement 1 class variable num each time you delete an instance
        print("I deleted this instance")

Start Python3 in the same hierarchy as the directory containing the above script file

Terminal


$ ls
class_test.py
$ cat class_test.py
class SampleClass:
    num = 0
    def __init__(self, number=1):
        SampleClass.num +=1 #Increment the class variable num by 1 each time an instance is created
        self.num = number #Store the argument number received from the generator at the time of instance creation in the instance variable num.
    def __del__(self):
        SampleClass.num -=1 #Decrement 1 class variable num each time you delete an instance
        print("I deleted this instance")
$
$ python3
>>>

* Import * the * class_test * module to create and delete an instance of the * SampleClass * class.

Terminal


>>> import class_test as ct
>>>
>>> sample_1 = ct.SampleClass()
>>> print(ct.SampleClass.num)
1
>>>
>>> print(sample_1.num)
1
>>>

(Points here)

  1. Created one instance of * SampleClass * class.
  2. The value of the class variable * num * that manages the number of instances is displayed as 1.
  3. In addition, the value of the instance variable * num * of the generated instance * sample_1 * is set to 1 set in the default argument of the constructor.

Terminal


>>> sample_2 = ct.SampleClass(number=4)
>>> print(ct.SampleClass.num)
2
>>> print(sample_2.num)
4
>>>

(Points here)

  1. I have created another instance of the * SampleClass * class.
  2. The value of the class variable * num * that manages the number of instances is displayed as 2.
  3. In addition, the value of the instance variable * num * of the generated instance * sample_2 * is set to 4 passed as an argument to the constructor when * sample_2 * is generated.

Terminal


>>> sample_3 = ct.SampleClass(number=15)
>>> print(ct.SampleClass.num)
3
>>> print(sample_3.num)
15
>>>

(Points here)

  1. Created another instance of the * SampleClass * class. You have now created a total of 3 instances.
  2. The value of the class variable * num * that manages the number of instances is displayed as 3.
  3. In addition, the value of the instance variable * num * that the generated instance * sample_3 * has is set to 15 that was passed as an argument to the constructor when * sample_3 * was generated.

From here, you can check the behavior of the destructor.

Terminal


>>> del sample_2
I deleted this instance
>>>

(Points here)

    • print ("This instance has been deleted") described in * destructor * of * SampleClass * class has been executed.
  1. You now have two instances.

Terminal


>>> print(ct.SampleClass.num)
2
>>> print(sample_1.num)
1
>>> print(sample_3.num)
15
>>> print(sample_2.num)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sample_2' is not defined
>>>

(Points here)

  1. The value of the class variable * num * that manages the number of instances is displayed as 2.
  2. When you delete the instance named * sample_2 *, you can see that the process of decrementing the class variable * num * described in * destructor * by 1 was executed properly.
  3. At this time, it was also confirmed that the instance variables of the two instances (* sample_1 * and * sample_3 *) other than the deleted instance did not change in value and were not unintentionally affected. ..

(Addition)

The code will be shorter if the * import * statement is as follows.

import statement (after change)


from class_test import SampleClass

Terminal


>>> from class_test import SampleClass
>>>
>>> sample_1 = SampleClass()
>>> print(SampleClass.num)
1
>>> print(sample_1.num)
1
>>>
>>> sample_2 = SampleClass(number=4)
>>> print(SampleClass.num)
2
>>> print(sample_2.num)
4
>>>

(Reference web page)

  1. How to use Python destructor [for beginners]
  2. [Python] Find the number of instances
  3. About Python classes
  4. @ ysk24ok's Qiita article "[Python] Import Stumbling Point"

Recommended Posts

Check the behavior of destructor in Python
About the behavior of Model.get_or_create () of peewee in Python
Check the asymptotic nature of the probability distribution in Python
Check the behavior when assigning Python
Check the operation of Python for .NET in each environment
Check the existence of the file with python
Check if the URL exists in Python
The result of installing python in Anaconda
Check the path of the Python imported module
The basics of running NoxPlayer in Python
In search of the fastest FizzBuzz in Python
How to check the memory size of a variable in Python
How to check the memory size of a dictionary in Python
[python] behavior of argmax
the zen of Python
Output the number of CPU cores in Python
[python] Check the elements of the list all, any
[Python] Sort the list of pathlib.Path in natural sort
Check if the characters are similar in Python
Get the caller of a function in Python
Match the distribution of each group in Python
View the result of geometry processing in Python
Make a copy of the list in Python
Check the date of the flag duty with Python
Find the divisor of the value entered in python
Find the solution of the nth-order equation in python
The story of reading HSPICE data in Python
[Note] About the role of underscore "_" in Python
Solving the equation of motion in Python (odeint)
Output in the form of a python array
Check the in-memory bytes of a floating point number float in Python
I made a program to check the size of a file in Python
Check if the string is a number in python
Easy way to check the source of Python modules
Experience the good calculation efficiency of vectorization in Python
Towards the retirement of Python2
How to get the number of digits in Python
Download the file in Python
Find the difference in Python
Existence check of external command in Python (like `which`)
Python --Check type of values
[python] Get the list of classes defined in the module
About the ease of Python
In Python, change the behavior of the method depending on how it is called
The story of FileNotFound in Python open () mode ='w'
Equivalence of objects in Python
Learn the design pattern "Chain of Responsibility" in Python
Implement the solution of Riccati algebraic equations in Python
Get the size (number of elements) of UnionFind in Python
Not being aware of the contents of the data in python
Check OpenSSL version of python 2.6
Reproduce the execution example of Chapter 4 of Hajipata in Python
Let's use the open data of "Mamebus" in Python
Check for the existence of BigQuery tables in Java
Implemented the algorithm of "Algorithm Picture Book" in Python3 (Heapsort)
[Python] Outputs all combinations of elements in the list
Implementation of quicksort in Python
Get the URL of the HTTP redirect destination in Python
A reminder about the implementation of recommendations in Python
About the features of Python
Reproduce the execution example of Chapter 5 of Hajipata in Python