How should I initialize multiple class arguments that came as chain and then calculate sum of them?
I’ve tried many ways but NOTHING
Do you have any idea?
>>> Chain(2.5)(2)(2)(2.5) # sum
9
>>> Chain(3)(1.5)(2)(3) # sum
9.5
>Solution :
In general, you’ll want to add a __call__
method to your class so that calling an instance returns a new instance. Your class should also subclass the type matching the result you want.
In this specific case, the new instance could, for example, maintain a running sum of the initial value and all successive arguments.
class Chain(float):
def __call__(self, x):
return Chain(self + x)
Then
>>> Chain(2.5)
2.5
>>> Chain(2.5)(2)
4.5
>>> Chain(2.5)(2)(2)
6.5
>>> Chain(2.5)(2)(2)(2.5)
9.0