![]() |
operator overloading won't work - 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: operator overloading won't work (/thread-28800.html) |
operator overloading won't work - MaartenRo - Aug-04-2020 Hi, When i run this code i get (0) + (1) = (2)while i should get Rood Groen Blauw + Geel Paars Cyaan = Rood Groen Blauw Geel Paars CyaanWhat am i doing wrong? Any input is much appreciated! class MyClass: def __init__(self, *args): self.Input = args def __add__(self, Other): Output = MyClass() Output.Input = self.Input + Other.Input return Output def __str__(self): Output = "" for Item in Self.Input: Output += Item Output += " " return Output Value1 = MyClass("Rood", "Groen", "Blauw") Value2 = MyClass("Geel", "Paars", "Cyaan") Value3 = Value1 + Value2 print("(0) + (1) = (2)" .format(Value1, Value2, Value3)) RE: operator overloading won't work - deanhystad - Aug-04-2020 First lets do the format problem. You need to use curly brackets instead of parenthesis in your format string. This is an easy mistake to make when copying code. Depending on the font, {} can look a lot like (). print("{0} + {1} = {2}".format('a', 'b', 'c'))Your operator overloading code doesn't work because you use Self instead of self in method __add___. When I ran your code Python told me exactly what and where the error was.
|