"<method>不带参数(给出1个)"但我没有给出任何参数

24 python methods call

我是Python的新手,我编写了这个简单的脚本:

#!/usr/bin/python3
import sys

class Hello:
    def printHello():
        print('Hello!')

def main():
    helloObject = Hello()
    helloObject.printHello()   # Here is the error

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

当我运行它(./hello.py)时,我收到以下错误消息:

Traceback (most recent call last):
  File "./hello.py", line 13, in <module>
    main()
  File "./hello.py", line 10, in main
    helloObject.printHello()
TypeError: printHello() takes no arguments (1 given)
Run Code Online (Sandbox Code Playgroud)

为什么Python认为我给出了printHello()一个参数,而我显然没有?我做错了什么?

ham*_*mar 40

该错误指的self是在调用类似方法时隐式传递的隐式参数helloObject.printHello().此参数需要明确包含在实例方法的定义中.它应该如下所示:

class Hello:
  def printHello(self):
      print('Hello!')
Run Code Online (Sandbox Code Playgroud)


小智 6

如果你想printHello作为实例方法,它应该总是接收self作为参数(ant python将隐式传递)除非你想printHello作为静态方法,否则你将不得不使用@staticmethod

#!/usr/bin/python3
import sys

class Hello:
    def printHello(self):
        print('Hello!')

def main():
    helloObject = Hello()
    helloObject.printHello()   # Here is the error

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

作为'@staticmethod'

#!/usr/bin/python3
import sys

class Hello:
    @staticmethod
    def printHello():
        print('Hello!')

def main():
    Hello.printHello()   # Here is the error

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)


Tor*_*ler 6

在对象实例上调用方法会将对象本身(通常self)返回给对象.例如,调用Hello().printHello()与调用相同,调用Hello.printHello(Hello())使用Hello对象的实例作为第一个参数.

相反,将您的printHello陈述定义为def printHello(self):