Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call function without parenthesis in python

Tags:

python

oop

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)
like image 987
Pr Mod Avatar asked Mar 06 '23 02:03

Pr Mod


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

like image 117
blue_note Avatar answered Mar 14 '23 22:03

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
like image 39
Peter Wood Avatar answered Mar 14 '23 22:03

Peter Wood