Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Chaining calls to a class in Python

This is from a past programming contest

Implement a class Chain that when called a number of times in a chain with numeric inputs, returns the sum of them.

>>> Chain(1)(2)(3)
6
>>> Chain(10) == 10
True

The thing is that in the first example the first call should return a number (i.e. 1), which is not callable. So how can the chain continue evaluating?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need a callable int:

>>> class Chain(int):
...     def __call__(self, other: int) -> Chain:
...         return Chain(self + other)
...
>>> Chain(10) == 10
True
>>> Chain(1)(2)(3)
6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading