0
0

More than 3 years have passed since last update.

class内関数で可変長配列*argsとselfを使った際のエラー

Last updated at Posted at 2021-08-24

問題

クラス内でdef sample(self, *arg)を定義した際に以下のようにselfが引数として扱われてしまう。

class Sampleclass:
    def sample(self, *args):
        print(args)
x = Sampleclass
x.sample(1, 2, 3)
>>> (2, 3)

解決方法

上の4行目でxにインスタンスを代入する際に()が抜けてました、、、
x = sampleclass()のようにすれば解決しました。初歩的すぎるけど()がなくても動いてしまうだけに引っかかってしまう人がいるかもしれないですね。

class Sampleclass:
    def sample(self, *args):
        print(args)
x = Sampleclass()
x.sample(1, 2, 3)
>>> (1, 2, 3)

追記

指摘いただいたようにクラス名の先頭を大文字に変更しました。
pythonのクラスについては追々勉強していきたいと思います。

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