call method without parenthesis in python

Question:

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)
Asked By: Pr Mod

||

Answers:

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.

Answered By: blue_note

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
Answered By: Peter Wood
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.