Class takes no arguments (1 given) [duplicate]

雨燕双飞 提交于 2021-02-08 12:13:17

问题


class MyClass:
    def say():
        print("hello")

mc = MyClass()
mc.say()

I am getting error: TypeError: say() takes no arguments (1 given). What I am doing wrong?


回答1:


This is because methods in a class expect the first argument to be self. This self parameter is passed internally by python as it always sends a reference to itself when calling a method, even if it's unused within the method

class MyClass:
    def say(self):
        print("hello")

mc = MyClass()
mc.say()
>> hello

Alternatively, you can make the method static and remove the self parameter

class MyClass:
    @staticmethod
    def say():
        print("hello")

mc = MyClass()
mc.say()
>> hello


来源:https://stackoverflow.com/questions/46448875/class-takes-no-arguments-1-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!