【问题标题】:Class takes no arguments (1 given) [duplicate]类不带参数(给定1个)[重复]
【发布时间】:2018-03-09 00:01:10
【问题描述】:
class MyClass:
    def say():
        print("hello")

mc = MyClass()
mc.say()

我收到错误:TypeError: say() takes no arguments (1 given)。我做错了什么?

【问题讨论】:

  • 我可以继续添加重复项,但您应该在 google 的心跳中找到这些链接。

标签: python python-3.x class exception methods


【解决方案1】:

这是因为类中的方法期望第一个参数是self。这个self 参数是由python在内部传递的,因为它在调用方法时总是发送对自身的引用,即使它在方法中没有使用

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

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

或者,您可以将方法设为静态并删除self 参数

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多