我是 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!')
关于python - "<method> takes no arguments (1 given)"但我没有给,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6614123/