1
1

More than 3 years have passed since last update.

デストラクタ

Last updated at Posted at 2020-01-31
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
#######################
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1