-1

Hi in a recent local programming contest there was a problem in which you had to define a class which takes chain-like parameters and returns their sum e.g. :

>>> Chain(2.5)(2)(2)(2.5) # sum
9
>>> Chain(3)(1.5)(2)(3) # sum
9.5

Best thing that I could write is this code:

class Chain():

    value = 0

    def __new__(self, num):
        self.value += num
        return self

obj = Chain(2)(3)
print(obj.value)

But the return type is a class not an int, furthermore I'm using a static property which is obviously wrong. Would appreciate any helps.

P.S. : Please note that that contest finished on January 7 2022 so I don't think there is any problem with posting this question.

buran
  • 13,682
  • 10
  • 36
  • 61
Mathemagician
  • 431
  • 4
  • 13
  • 2
    You'll want to look at the `__call__` and `__str__` methods, not `__new__`… – deceze Jan 27 '22 at 14:10
  • @deceze Thanks I could write the answer using your suggestion. I also changed the title to represent the question and the answer better. However I'm not sure whether I should delete the question (since it has no answer and your comment is the correct answer) or keep it. Maybe a better title for the question can make it useful to others who may face the same problem – Mathemagician Jan 27 '22 at 14:17
  • @AvSaba please provide the working code – Manish Shetty Jan 27 '22 at 14:22
  • @sahasrara62 Yes your link answers the question. It's interesting that the question was asked the same day that the contest happened. – Mathemagician Jan 27 '22 at 16:12
  • @AvSaba no idea about what context you are talking, but i have seen this question so marked it as duplicate – sahasrara62 Jan 27 '22 at 17:11

1 Answers1

2

You can inherit from float (as you need to support decimal numbers) and implement __call__ like so:

class Chain(float):
    def __call__(self, value):
        return self.__class__(self+value)

>>> Chain(3)(1.5)(2)(3) # sum
9.5
>>> Chain(2.5)(2)(2)(2.5) # sum
9.0
Bharel
  • 23,672
  • 5
  • 40
  • 80