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()
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('#######################')
2の実行結果
I am Tom. Hello.
run run run
#######################
Good-Bye
print('#######################')の後に、
コードがなく、
personオブジェクトが使われないとなった場合に、
デストラクタであるdel関数が呼び出される。
2の様にではなく、
#################の上に
Good-Byeを出力させたい場合は、
del personで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('#######################')
3の実行結果
I am Tom. Hello.
run run run
Good-Bye
#######################