LoginSignup
1
0

More than 5 years have passed since last update.

[Python3]インスタンスオブジェクト内のローカル変数について

Posted at
class Sample:
    A = 1 #クラス変数

    def __init__(self):
        self.b = 2 #インスタンス変数
        c = 3 #ローカル変数


sample = Sample()

print(Sample.A) #クラスオブジェクトからクラス変数を参照
print(sample.A) #インスタンスオブジェクトからクラス変数を参照
print(sample.b) #インスタンスオブジェクトからインスタンス変数を参照
#print(sample.c)#インスタンスオブジェクトからインスタンスオブジェクトのローカル変数を参照

最後のprint(sample.c)は実行できない.
実行しようとするとAttributeErrorがでる.

他のスコープで参照される場合はインスタンス変数に,参照されない場合はselfをつけないでローカル変数にする.
いままでとりあえずselfをつけていたので使い分けるようにしたい.

間違いとか補足があればコメントをお願いします.
まだまだ勉強が足りないので.

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