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 multiple class arguments

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?

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

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