LoginSignup
0
0

More than 1 year has passed since last update.

Pythonのself

Posted at

はじめに

最近pythonを勉強していて出会ったselfが少し曖昧だったので少しまとめておく。

クラスとは

オブジェクトを生成する型のようなもの。
以下のように使われる。

qiita.py
class className():
    pass

instance = className()

selfとは

インスタンス自身のこと。
以下のように使われる。

class className():
    def __init__(self, strA, strB):
        self.strA = strA
        self.strB = strB

instance = className("hello", "qiita")
print(instance.strA)
print(instance.strB)

このコードでいうinstanceselfなのではないかという認識。

注意点

これは面白いなと思ったのがpythonはクラス変数にもインスタンス変数にも値がある場合は、インスタンス変数を優先して参照する。

class className():
    strA = "Hello qiita"
    def __init__(self):
        print("1: " + self.strA)
        self.strA = "Hello World!"
        print("2: " + self.strA)
        strA = "Hello python"
        print("3: " + self.strA)
 
test = className()

結果は

1: Hello python
2: Hello World!
3: Hello World!

strAよりもself.strAが優先される。

最後に

ちょっと知らなかったことに出会ったのでまとめてみました。間違いがあったらぜひ教えてください。

0
0
1

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