【学習記録】Python基礎 Object Methods/self

今日はこちらのページのObject Methodsとself Parameterについて勉強しました。

www.w3schools.com

基礎から勉強してることでPythonのコードがだんだん読みやすくなってきました。

以下箇条書きで学んだことをメモします。

Object Methods

Object Methodsについては以下の説明があった。

Objects can also contain methods. Methods in objects are functions that belong to the object.
Let us create a method in the Person class:

オブジェクトはメソッドも含むことができる。
オブジェクトが持つメソッドは関数に紐づく関数である。

クラスにメソッドを定義するサンプルコードは以下。

class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def myfunc(self):
        print("Hello my name is " + self.name)

u1 = User("user1", 15)
u1.myfunc()

Userクラスにmyfuncをメソッドとして定義しているので、Userクラスをu1に代入するだけでu1もmyfunc()が呼び出せる。

ローカルで動作確認。
f:id:JunpeiNakasone:20210308225804p:plain

The self Parameter

selfについては以下の説明があった。

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:

selfパラメータはクラスの現在のインスタンスへのリファレンスで、クラスに属する変数にアクセスする際に使用される。
selfという名称以外でも使えるが、クラスが持つ関数の最初のパラメータである必要がある。

パラメータをself以外の名称にして動作確認してみました。

class User:
    def __init__(test, name, age):
        test.name = name
        test.age = age

    def myfunc(foo):
        print("Hello my name is " + foo.name)

u1 = User("user1", 15)
u1.myfunc()

ローカルで動作確認。
f:id:JunpeiNakasone:20210309064541p:plain

確かにself以外の名称にしてもエラーにならず動作することが確認できました。
ただPythonの仕様としてはエラーにならないものの、pylintの方で警告は出るようです。

特にself以外の名称にしないといけない場面も思い浮かばないので、基本的には慣習に従ってselfという名称を使う方が良さそうな印象を受けました。