LoginSignup
0
0

More than 3 years have passed since last update.

[Python]No value for argument 'self' in unbound method callが出た

Posted at

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 だと動かないと理解

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