Search code examples
pythonclassreturninstance

Return string instead of class in Python


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.


Solution

  • 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