0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】クラス変数と__init__ってどっちが最初に実行されるの?

Last updated at Posted at 2019-12-09

pythonを書いていてふと思いました。
「クラス変数と__init__はどっちが先に実行されるんだ???」
深掘りはしません。小ネタです。
最後まで読むにはもったいないくらいの小ネタなので最初に結果書いちゃいます。

結果

最初にクラス変数の処理が行われ、その後に__init__が実行されます。

検証

クラス変数と__init__にそれぞれprint()を書きます。その実行結果からどちらが先に表示されたかを確認します。

test.py
class main:

    s = 'クラス変数が定義されました。'
    print(s)

    def __init__(self):
        s = '__init__が実行されました。'
        print(s)

if __name__ == '__main__':
    main()
結果
$ python test.py
クラス変数が定義されました。
__init__が実行されました。

先にクラス変数が実行され、その後に__init__が実行されています。
では、次は__init__の下にクラス変数を定義してみましょう。コードは汚くなりますが検証なので...

test.py
class main:

    def __init__(self):
        s = '__init__が実行されました。'
        print(s)

    s = 'クラス変数が定義されました。'
    print(s)


if __name__ == '__main__':
    main()
結果
$ python test.py
クラス変数が定義されました。
__init__が実行されました。

結果は変わっていません。どちらを上に書いても必ずクラス変数から実行されることがわかりました。
それだけです。

追記

コメントで

main()を呼ばずに実行してみてください。
面白い結果になりますよ。

と頂き、やってみたところクラス変数の部分のみ実行されました。わかりやすく説明をして頂いたのでコメントを参照してください。クラスを実行しなくともクラス内やメソッド内の処理が参照できることがわかると思います。
一生初心者から抜け出せません。でも楽しいです。

0
0
4

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?