-1

In this program the output is not what I would expect:

class example(object):
    def __init__(self, foo,bar):
        self.foo = foo
        self.bar  = bar
    def what_are_you():
        print(foo,bar)
        print("This doesn't work either")

a = example("aaa","bbb")
a.what_are_you
#should return "aaa bbb"
print(a.what_are_you)
print(a.foo,a.bar)

Instead it outputs nothing. This is the whole output:

<bound method example.what_are_you of <__main__.example object at 0x000002A9574B4710>>
aaa bbb

Process returned 0 (0x0)        execution time : 0.041 s
Alec
  • 8,529
  • 8
  • 37
  • 63
Orión González
  • 309
  • 2
  • 14
  • 2
    you have to use `self.` in `def what_are_you(self)` and `print(self.foo, self.bar)`. And you forgot `()` in `a.what_are_you()` – furas May 19 '19 at 02:42

2 Answers2

1

By not including parentheses, you're printing the function object, not calling the function. To call the function, put parentheses after it.

print(a.what_are_you())

will print the value of what_are_you() (whatever is in the return statement)

Alec
  • 8,529
  • 8
  • 37
  • 63
  • That returns: Traceback (most recent call last): File "C:\Users\Orion\AppData\Local\Programs\Python\Python36\Lib\site-packages\pygame\examples\chimp.py", line 13, in print(a.what_are_you()) TypeError: what_are_you() takes 0 positional arguments but 1 was given – Orión González May 19 '19 at 02:46
0

As I see now, you're printing stuff, not returning stuff, so you might need to use:

a.what_are_you()

And in your function, you need to use self to get the variable:

def what_are_you(self):
    print(self.foo,self.bar)
    print("This doesn't work either")
U13-Forward
  • 69,221
  • 14
  • 89
  • 114