1
class Person(object):
def __init__(self, name):
self.name = name
def say_something(self):
print('I am {}. Hello'.format(self.name))
self.run(3)
def run(self, num):
print('run '*num)
def __del__(self):
print('Good-Bye')
person = Person('Tom')
person.say_something()
Execution result of 1
I am Tom. Hello.
run run run
Good-Bye
2
class Person(object):
def __init__(self, name):
self.name = name
def say_something(self):
print('I am {}. Hello.'.format(self.name))
self.run(3)
def run(self, num):
print('run ' * num)
def __del__(self):
print('Good-Bye')
person = Person('Tom')
person.say_something()
print('#######################')
Execution result of 2
I am Tom. Hello.
run run run
#######################
Good-Bye
After print ('#######################') No code, If the person object is no longer used The destructor del function is called.
Not like 2 ####################### On top of the If you want to output Good-Bye, You can delete the person object with del person.
3
class Person(object):
def __init__(self, name):
self.name = name
def say_something(self):
print('I am {}. Hello.'.format(self.name))
self.run(3)
def run(self, num):
print('run ' * num)
def __del__(self):
print('Good-Bye')
person = Person('Tom')
person.say_something()
del person
print('#######################')
Execution result of 3
I am Tom. Hello.
run run run
Good-Bye
#######################