“ 不带参数(给定1个)”,但我不给

发布于 2021-01-29 17:17:17

我是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()

运行它(./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)

为什么Python认为我给出printHello()了论据而我却没有给出?我做错了什么?

关注者
0
被浏览
37
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    错误是指self调用诸如之类的方法时隐式传递的隐式参数helloObject.printHello()。该参数需要明确包含在实例方法的定义中。它看起来应该像这样:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看