LoginSignup
1
1

More than 1 year has passed since last update.

[Python] takes 0 positional arguments but 1 was givenエラーの解消

Posted at

経緯

Pythonでtakes 0 positional arguments but 1 was givenとエラーが出た。

直訳すると「引数は0のはずなのに一つ渡されている」とのこと。一つも渡していないはずなのに...。

class Test:
  def test_method():
    print("test")

t = Test()
t.test_mothod() # Test.test_method() takes 0 positional arguments but 1 was given 

原因と解決方法

Pythonのクラス内で定義した関数を外から呼び出す場合、自動的に第一引数にレシーバーが渡される。それを引き取るための引数を定義してあげる必要がある。慣習的にはselfを使う。

class Test:
  def test_method(self): # selfを追記
    print("test")

ちょっと確認

selfの中には何が入っているのか?

class Test:
  def test_method(self):
    print(self) # <__main__.Test object at 0x10ca28b80>

t = Test()
print(t) # <__main__.Test object at 0x10ca28b80>
t.test_method()

同じオブジェクトが出力されているのが確認できる。selfの中にはレシーバのインスタンス自身が格納されていることが確認できる。

self以外でもいいのか?

class Test:
  def test_method(okame):
    print(okame) # <__main__.Test object at 0x10ca28b80>

t = Test()
t.test_method()

全く問題ない。わざわざ変える必要もないけど。

class Test:
  def test_method(self, second):
    print(self) # <__main__.Test object at 0x10ca28b80>
    print(second) # 2

t = Test()
t.test_method(2)

第2引数は第1引数のように呼び出す。非常にややこしい。
t.test_method(2) ≒ t.test_method(t, 2)のようなものと考えればわかりやすいか。

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