Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Addition of 2 classes
#1
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
Reply
#2
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__.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Multiply and Addition in the same loop statement with logic. joelraj 2 998 Feb-02-2023, 04:33 AM
Last Post: deanhystad
  forloop to compute sum by alternating from addition to subtraction JulianZ 3 1,762 Apr-02-2022, 09:36 AM
Last Post: DeaD_EyE
  addition for elements in lists of list ridgerunnersjw 3 3,039 Sep-15-2019, 07:11 AM
Last Post: perfringo
  multiplication by successive addition Zebrol 1 3,471 Sep-14-2019, 05:37 PM
Last Post: ichabod801
  Python 2.7 Addition to dict is too slow VolanD 6 3,971 May-04-2018, 09:24 AM
Last Post: Gribouillis
  Trying to create a python exe for an addition problem with an odd variable Python_Newb 0 2,130 Nov-30-2017, 12:18 PM
Last Post: Python_Newb
  Using classes? Can I just use classes to structure code? muteboy 5 4,978 Nov-01-2017, 04:20 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020