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

python selfについて

Posted at

selfがある場合について

class Dog:
    def __init__(self,name):
        self.name = name

    def bark(self):
        print(f"{self.name}がワンと吠えた")

dog1 = Dog("ポチ")
dog2 = Dog("ハチ")

dog1.bark() # ポチ がワン!と吠えた
dog2.bark() # # ハチ がワン!と吠えた

インスタンスごとに別のデータを持てる

selfがない場合について

class Dog:
    def __init__(self,name):
        Dog.name = name

    def bark()
        print(f"{Dog.name}がワンと吠えた")

dog1 = Dog("ポチ")
dog2 = Dog("ハチ")

dog1.bark()  # ハチ がワン!と吠えた
dog2.bark()  # ハチ がワン!と吠えた

どの犬も最後に設定した「ハチ」になっちゃう
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?