I decided to use str for printing the contents of a tree in tree-like structure,using something like
print tree
The nodes of the tree are all objects of user-created classes and I overload their __str__
magic method in order to use the child nodes' str after indent t tabs like that
def __str__ (self,t=0) :`
return t*'\t' + str(self.label) +':' +'\n'+ str(self.l,t+1)+'\n'+str(self.right,t+1)+'\n'
However I can't call str
with that t
parameter,but I can call node.__ str__(t=4)
.Isn't str
,only shortcut to the magic method?Or is that because the parser rejects additional params to str
without checking the magic method?
P.S. I am interested in the behaviour.I know that's not the best way to print a tree,it was a hack ;)
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.
The print statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object.
__str__ is a special method, like __init__ , that is supposed to return a string representation of an object. For example, here is a str method for Time objects: # inside class Time: def __str__(self): return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
Internally, Python will call the __str__ method automatically when an instance calls the str() method. Note that the print() function converts all non-keyword arguments to strings by passing them to the str() before displaying the string values.
Imagine it this way.
def str(obj):
try:
return obj.__str__()
except ...:
...
Just because __str__
can take more parameters, doesn't mean that str
is configured to pass those parameters through.
If you have a Class C
with a method __str__(self, t=0)
, str(c)
will call C.__str__(c)
which sets t to zero as declared. str()
itself only accepts one argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With