7

what modification i would need to do in the below function computeDifference to get result printed in the console, instead of object message.

i know i need to add parenthesis () to call function to get the result printed in the console, but is there any other way to print the result?

class Difference1:
    def __init__(self, a):
        self.__elements = a

    def computeDifference(self):
        self.difference =  max(self.__elements)- min(self.__elements)
        return self.difference

a = [5,8,9,22,2]
c = Difference1(a)
print(c.computeDifference)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Pr Mod
  • 261
  • 2
  • 5
  • 15

2 Answers2

10

Make it a property

class Difference1:
@property
def computeDifference(self):
   ...

print(c.computeDifference)

However, I would change the name to difference. The idea of a property is that you shouldn't know or care whether the value is computed at that time or is stored as an attribute of the object. See uniform access principle.

blue_note
  • 27,712
  • 9
  • 72
  • 90
3

You could add a magic function:

class Difference1:
    ...
    def __str__(self):
        return str(self.computeDifference())
    ...

>>> a = [5,8,9,22,2]
>>> c = Difference1(a)
>>> print(c)
20
Peter Wood
  • 23,859
  • 5
  • 60
  • 99