开发者

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) :`
   开发者_JS百科 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 ;)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜