TypeError: method() takes 1 positional argument but 2 were given

前端 未结 9 1117
孤街浪徒
孤街浪徒 2020-11-22 05:02

If I have a class...

class MyClass:

    def method(arg):
        print(arg)

...which I use to create an object...

my_objec         


        
9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 05:49

    In simple words.

    In Python you should add self argument as the first argument to all defined methods in classes:

    class MyClass:
      def method(self, arg):
        print(arg)
    

    Then you can use your method according to your intuition:

    >>> my_object = MyClass()
    >>> my_object.method("foo")
    foo
    

    This should solve your problem :)

    For a better understanding, you can also read the answers to this question: What is the purpose of self?

提交回复
热议问题