Addition of 2 classes - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Addition of 2 classes (/thread-16135.html) |
Addition of 2 classes - Naito - Feb-15-2019 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)
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 RE: Addition of 2 classes - DeaD_EyE - Feb-15-2019 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) 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__ .
|