Vor
Vor

Reputation: 35109

why use str() is better than __str__()

Some time ago I asked one question, and a lot of people suggested me to change __str__() to str(some object).

for example:

e_address   = f_name+l_name+year.__str__()+day.__str__()

Change to :

e_address   = f_name+l_name+str(year)+str(day)

So my question is why it is better? Are there any performance difference, or it is more pythonic way of programming?

Upvotes: 2

Views: 239

Answers (2)

vy32
vy32

Reputation: 29645

It's less typing and the code is easier to read.

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1121534

__str__() is the hook method that str() calls if it is present. The str() function will fall back to a sensible default if no such method is defined. Hooks are there to override the default behaviour, and you should not assume they are always implemented.

Moreover, it's more readable to just use the str() callable.

Upvotes: 8

Related Questions