<<方法>不接受任何参数(给定1个)"但是我什么也没给 [英] "<method> takes no arguments (1 given)" but I gave none

查看:70
本文介绍了<<方法>不接受任何参数(给定1个)"但是我什么也没给的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Python and I have written this simple script:

#!/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)时,出现以下错误消息:

When I run it (./hello.py) I get the following error message:

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()一个参数,而我却没有给?我做错了什么?

Why does Python think I gave printHello() an argument while I clearly did not? What have I done wrong?

推荐答案

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

The error is referring to the implicit self argument that is passed implicitly when calling a method like helloObject.printHello(). This parameter needs to be included explicitly in the definition of an instance method. It should look like this:

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

这篇关于&lt;&lt;方法&gt;不接受任何参数(给定1个)"但是我什么也没给的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆