Python初心者です。
selfの考え方をイマイチ理解出来ておらず、地味に躓いたのでメモ
hello.py
class HelloWorld:
def __init__(self):
self.message = 'Hello,World'
def gree(self):
print(self.message)
sample.py
import hello
h = hello.HelloWorld
h.gree()
このコードだとh.gree()で「No value for argument 'self' in unbound method call」というエラーになる。
エラーの内容は関数greeの引数selfがないよというもの
selfって関数呼び出し時の引数に指定しなくていいんじゃないんだっけ?と躓いた。
sample.pyのコードを以下にすることで解決
sample.py
import hello
h = hello.HelloWorld()
h.gree()
参考
sample.py
h = hello.HelloWorld
print(type(h))
h = hello.HelloWorld()
print(type(h))
<class 'type'>
<class 'hello.HelloWorld'>
hello.HelloWorld だとクラス定義を代入
hello.HelloWorld()だとクラスのインスタンスを代入
selfはクラスのインスタンス情報を保持するものなので、hello.HelloWorld だと動かないと理解