Python has a corresponding special destructor (destructor) method named __del__ (). However, because Python has garbage collection mechanisms (counting by reference), this function is not executed until all references to the instance object are cleared. A destructor in Python is a method of providing special handling functionality before an instance is released, which is usually not implemented because the instance is rarely explicitly released.
In the following example, we create (and overwrite) the __init__ () and the __del__ () constructor and the destructor, and then initialize the class and give the same object many aliases. The ID () built-in function can be used to determine the three aliases that refer to the same object. The final step is to use the DEL statement to clear all aliases to show how many times the destructor was invoked.
Copy Code code as follows:
#!/usr/bin/env python
#coding =utf-8
Class P ():
def __del__ (self):
Pass
Class C (P):
def __init__ (self):
print ' initialized '
def __del__ (self):
P.__del__ (self)
print ' deleted '
C1 = C ()
C2 = C1
C3 = C1
Print ID (c1), ID (C2), ID (C3)
Del C1
del C2
del C3
Python does not provide any internal mechanism to track how many instances of a class have been created, or what these instances are. If you need these features, you can explicitly add some code to the class definition or __init__ () and __del__ (). The best way to do this is to use a static member to record the number of instances. It is dangerous to keep track of instance objects by saving their references, because you have to manage them properly, or your references may not be able to be released (because there are other references)! Look at the following example:
Copy Code code as follows:
Class INSTCT (object):
Count = 0
def __init__ (self):
Instct.count + 1
def __del__ (self):
Instct.count-= 1
def howmany (self):
Return Instct.count
A = INSTCT ()
b = INSTCT ()
Print B.howmany ()
Print A.howmany ()
Del b
Print A.howmany ()
Del A
Print Instct.count
All outputs:
Copy Code code as follows:
Initialized
4372150104 4372150104 4372150104
Deleted
********************
2
2
1
0