Michael Durrant
Michael Durrant

Reputation: 96554

python interactive - where does instance method output go?

When I do a simple look I get output:

>>> 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

but when i use a class instance method I get:

$ 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

Where can I see the "hello" ?

First timer pythonist here, coming from Ruby and irb

Upvotes: 0

Views: 38

Answers (1)

John Kugelman
John Kugelman

Reputation: 361977

Two problems.

  1. The method is missing a self argument. That's the reason for the error hi() takes no arguments (1 given). The "1 given" argument is the implied self.

    class Bob:
        def hi(self):
            print "hello"
    
  2. You need to add empty parentheses to call it. Without them you just get a printout of the method itself rather than the result of the method.

    >>> Bob().hi()
    hello
    

Upvotes: 1

Related Questions