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

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

问题描述

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

#!/usr/bin/python3导入系统班级您好:定义打印Hello():打印('你好!')定义主():你好对象 = 你好()helloObject.printHello() # 这里是错误如果 __name__ == '__main__':主要的()

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

<块引用>

回溯(最近一次调用最后一次):文件./hello.py",第 13 行,位于 <module>主要的()文件./hello.py",第 10 行,在主目录中helloObject.printHello()类型错误:printHello() 不接受任何参数(给定 1 个)

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

解决方案

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

class 你好:def printHello(self):打印('你好!')

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

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)

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

解决方案

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;方法&gt;不接受任何参数(给定 1 个)"但我没有给的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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