LoginSignup
0
1

More than 3 years have passed since last update.

コンストラクタとデストラクタ

Last updated at Posted at 2020-08-25

コンストラクタ

オブジェクトを作る初めのときに呼ばれるもの

qiita.py
class Person(object):
    def __init__(self,name):
        self.name = name

デストラクタ

オブジェクトがなくなるときに呼ぶ物
使われなくなったときに呼び出される

qiita.py
class Person(object):
    def __init__(self,name):
        self.name = name

    def say_something(self):
        print("I am {}. hello".format(self.name))
        self.run()

    def run(self):
        print("run")

    #ここがデストラクタ
    def __del__(self):
        print("good bye")

実行結果
スクリーンショット 2020-08-16 20.37.39.png

全てのコードが使われた時点で呼び出される
スクリーンショット 2020-08-16 20.39.26.png

明示的に使いたい場合

qiita.py
del person

実行結果
スクリーンショット 2020-08-16 20.42.57.png

0
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
0
1