首页 > 解决方案 > 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

标签: python

解决方案


两个问题。

  1. 该方法缺少self参数。这就是错误的原因hi() takes no arguments (1 given)。“1 给定”参数是隐含的self

    class Bob:
        def hi(self):
            print "hello"
    
  2. 您需要添加空括号来调用它。没有它们,您只会得到方法本身的打印输出,而不是方法的结果

    >>> Bob().hi()
    hello
    

推荐阅读