我是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()
Run Code Online (Sandbox Code Playgroud)
当我运行它(./hello.py)时,我收到以下错误消息:
Run Code Online (Sandbox Code Playgroud)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()一个参数,而我显然没有?我做错了什么?
ham*_*mar 40
该错误指的self是在调用类似方法时隐式传递的隐式参数helloObject.printHello().此参数需要明确包含在实例方法的定义中.它应该如下所示:
class Hello:
def printHello(self):
print('Hello!')
Run Code Online (Sandbox Code Playgroud)
小智 6
如果你想printHello作为实例方法,它应该总是接收self作为参数(ant python将隐式传递)除非你想printHello作为静态方法,否则你将不得不使用@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()
Run Code Online (Sandbox Code Playgroud)
作为'@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()
Run Code Online (Sandbox Code Playgroud)
在对象实例上调用方法会将对象本身(通常self)返回给对象.例如,调用Hello().printHello()与调用相同,调用Hello.printHello(Hello())使用Hello对象的实例作为第一个参数.
相反,将您的printHello陈述定义为def printHello(self):
| 归档时间: |
|
| 查看次数: |
19173 次 |
| 最近记录: |