Python Forum

Full Version: Addition of 2 classes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello
i want too add class A with class B but this problem occurs
(i want to experiment with the code so that's why i made 2 classes)
Error:
TypeError: unsupported operand type(s) for +: 'int' and 'Chair'
class Table:
    def __init__(self, x):
        self.x = x
        self.y = Chair(self)

    def __add__(self, other):
        self.x + self.y


class Chair:
    def __init__(self, y):
        self.y = y


taw = Table(1)
kor = Chair(20)
print(taw + kor)
im still kinda new with Object-Oriented Programming
thank you
You have forgotten to return the value and you did not use other.

class Table:
    def __init__(self, x):
        self.x = x
 
    def __add__(self, other):
        return self.x + other.y
    
    def __radd__(self, other):
        return self.x + other.y 
 
class Chair:
    def __init__(self, y):
        self.y = y
 
 
taw = Table(1)
kor = Chair(20)
print(taw + kor)
print(kor + taw)
Output:
21 21
The __radd__ method is called, when the left object has no __add__ method.
So you have to implement the __add__ and __radd__ methods only in one class.
If you want to do addition with Chair and other objects, you have to implement there also __add__ and __radd__.