Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why str can't get a second parameter,when __str__ can?

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 ;)

like image 330
Alexander Ivanov Avatar asked Sep 08 '11 19:09

Alexander Ivanov


People also ask

What is the purpose of __ Str__ method?

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.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

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.

What is def __ str __?

__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)

How do you call the _ _str_ _ method?

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.


2 Answers

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.

like image 83
Dietrich Epp Avatar answered Sep 22 '22 12:09

Dietrich Epp


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.

like image 42
rocksportrocker Avatar answered Sep 21 '22 12:09

rocksportrocker