Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (16.4k points)

I've tried to include a class object with a number, but I don't know how to add class objects with 2 numbers. 

For example, consider the below code:

class A:

    def __add__(self, b):

        return something

I knew how to add with one number:

object = A()

print(object + 1)

But, how can I add them like this?

object = A()

print(object + 1 + 2)

Whether I need to use *args for the add class method? 

1 Answer

0 votes
by (26.4k points)

You can use + operator seperately, you can't use multiple arguments.

For your model, object + 1 + 2 truly is (object + 1) + 2. On the off chance that (object + 1) creates an object that has a __add__ method, at that point Python will call that technique for the second operator. 

You can also return the other instance of  A here:

>>> class A:

...     def __init__(self, val):

...         self.val = val

...     def __repr__(self):

...         return f'<A({self.val})>'

...     def __add__(self, other):

...         print(f'Summing {self} + {other}')

...         return A(self.val + other)

...

>>> A(42) + 10

Summing A(42) + 10

<A(52)>

>>> A(42) + 10 + 100

Summing A(42) + 10

Summing A(52) + 100

<A(152)>

Interested to learn python in detail? Come and Join the python course.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...