python - python interactive - 实例方法输出在哪里?
问题描述
当我做一个简单的外观时,我得到了输出:
>>> for x in range(1, 11):
... print repr(x).rjust(2), repr(x*x).rjust(3),
... print repr(x*x*x).rjust(4)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
但是当我使用类实例方法时,我得到:
$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Bob():
... def hi():
... print("hello")
...
>>> Bob()
<__main__.Bob object at 0x7f5fbc21b080>
>>> Bob().hi
<bound method Bob.hi of <__main__.Bob object at 0x7f5fbc21afd0>>
>>> Bob().hi()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: hi() takes 0 positional arguments but 1 was given
我在哪里可以看到“你好”?
这里的第一个 Pythonist,来自 Ruby 和irb
解决方案
两个问题。
该方法缺少
self
参数。这就是错误的原因hi() takes no arguments (1 given)
。“1 给定”参数是隐含的self
。class Bob: def hi(self): print "hello"
您需要添加空括号来调用它。没有它们,您只会得到方法本身的打印输出,而不是方法的结果。
>>> Bob().hi() hello
推荐阅读
- php - CodeIgniter 会话数据在身份验证期间显示为空
- vba - 如何在公式中使用引号以及活动单元格公式
- angular - 如何清除Angular2中的所有输入字段
- swift - 协议仅由 struct 或 immutable 实现
- c# - 为什么有些 C# 方法使用对象来传递参数,而不是直接传递它们?
- apache-kafka - Kafka PersistentWindowStore 再平衡机制
- linux - 如何在 aws ec2 实例上升级打包程序
- javascript - 如何使用 pixi.js 获取 PIXI.Graphics 实例的边界?
- python - 如何创建具有以下给定条件的二进制矩阵:
- javascript - 如何使用 JavaScript 将文本菜单链接更改为图像?