I need to understand how OOP works with magic methods by changing some lines in the code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I need to understand how OOP works with magic methods by changing some lines in the code

class SpecialString: def __init__(self, cont): self.cont = cont def __truediv__(self, other): line = "=" * len(other.cont) return "\n".join([self.cont, line, other.cont]) spam = SpecialString("spam") hello = SpecialString("Hello world!") print(spam / hello) #I want to print "spam" only with command of print(spam) without (/hello) #I want to print "====" (specific number of times) using print command and OOP

26th Jun 2022, 6:01 AM
Ibrahim Alzein
Ibrahim Alzein - avatar
4 Answers
+ 1
__truediv__ dunder was meant for floating point division. Why are you even using it in the class when the method does nothing related to floating point division? it is doing string multiplication instead. To support print() function, implement __str()_ dunder
26th Jun 2022, 6:57 AM
Ipang
+ 1
This code was copied from (python core) course the aim of this to learn how to change the functionality of operators, and unfortunately I can't understand how it works
26th Jun 2022, 7:07 AM
Ibrahim Alzein
Ibrahim Alzein - avatar
+ 1
Thanks this is very helpful, I need more time to focus on them .. but they seem very handy
26th Jun 2022, 9:18 AM
Ibrahim Alzein
Ibrahim Alzein - avatar