繁体   English   中英

“<method> 没有 arguments(1 个给定)”但我没有给</method>

[英]“<method> takes no arguments (1 given)” but I gave none

我是 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()一个论点,而我显然没有? 我做错了什么?

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

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

如果您希望printHello作为实例方法,它应该始终接收 self 作为参数(ant python 将隐式传递)除非您希望printHello作为 static 方法,否则您必须使用@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()

作为'@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()

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

相反,将您的printHello语句定义为def printHello(self):

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM