0

Is it possible to add in a third string in this magic method?

#i am trying to add in "sandwich" to the example code. #thanks in advance class SpecialString: def __init__(self, cont): self.cont = cont def __truediv__(self, other, other2): line = "=" * len(other.cont) return "\n".join([self.cont, line, other.cont, other2.cont]) spam = SpecialString("spam") hello = SpecialString("Hello world!") sandwich = SpecialString("sandwich") print(spam / hello / sandwich)

11th Mar 2017, 1:56 AM
boomshakalaka
boomshakalaka - avatar
1 Odpowiedź
+ 6
it is not possible to add another parameter to the __truediv__ magic method. But you can make the print statement work as you want by changing the class like this: class SpecialString: def __init__(self, cont): self.cont = cont def __truediv__(self, other): line = ''=' * 10 # I put 10 equal characters here for simplicity return '\n'.join([str(self), line, str(other)]) # because it will work with strings which have no 'cont' attribute def __rtruediv__(self, other): # this method will be called when this object is to the right of the operator line = '=' * 10 return '\n'.join([str(other), line, str(self)]) # this time other comes first def __str__(self): # this will be called by str(self) return self.cont spam = SpecialString("spam") hello = SpecialString("Hello world!") sandwich = SpecialString("sandwich") print(spam / hello / sandwich)
11th Mar 2017, 3:15 PM
Ulisses Cruz
Ulisses Cruz - avatar