6

I have a class

class ActivationResult(object):

    def __init__(self, successful : bool):
        self._successful = successful

    def getSuccessful(self) -> bool:
        return self._successful

And a test

def testSuccessfulFromCreate(self):

    target = ActivationResult(True)

    self.assertEquals(target._successful, True)
    self.assertEquals(target.getSuccessful, True)

The first assert is good, but the second one fails with AssertionError: <bound method ActivationResult.getSuccess[84 chars]EB8>> != True

The same thing happens, when I try to print it. Why?

habakuk
  • 2,712
  • 2
  • 28
  • 47
  • 1
    The error message is pretty clear - you're comparing **the method itself**, rather than the value it would return if called. Also, there's no need for get/set in Python; either access the attribute directly or use a `@property`. – jonrsharpe Mar 05 '15 at 14:20
  • @PM2Ring: I tried to use https://www.python.org/dev/peps/pep-3107/ as mentioned in http://stackoverflow.com/a/21384492/254041 (and it doesn't produce any errors or warnings). – habakuk Mar 05 '15 at 15:20
  • @PM2Ring that's a function annotation – jonrsharpe Mar 05 '15 at 15:35

1 Answers1

9

You are getting the method, not calling it.
Try :

self.assertEquals(target.getSuccessful(), True)  # With parenthesss

It's OK the first time because you get the attribute _successful, which was correctly initialized with True.
But when you call target.getSuccessful it gives you the method object itself, where it seems like you want to actuall call that method.


Explanation

Here is an example of the same thing that happens when you print an object's method:

class Something(object):
    def somefunction(arg1, arg2=False):
        print("Hello SO!")
        return 42

We have a class, with a method.
Now if we print it, but not calling it :

s = Something()
print(s.somefunction)  # NO parentheses
>>> <bound method Something.somefunction of <__main__.Something object at 0x7fd27bb19110>>

We get the same output <bound method ... at 0x...> as in your issue. This is just how the method is represented when printed itself.

Now if we print it and actually call it:

s = Something()
print(s.somefunction())  # WITH parentheses
>>>Hello SO!
>>>42

The method is called (it prints Hello SO!), and its return is printed too (42)

d6bels
  • 1,432
  • 2
  • 18
  • 30
  • Well I realize it might just be a typo and you forgot the parentheses, but as you've put "beginner" in the title I thought I'd explain something I hope useful. – d6bels Mar 05 '15 at 14:37
  • Thanks for your answer - very helpful for a deeper understanding. – habakuk Mar 05 '15 at 15:27