2

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?

4

2 回答 2

8

__str__()str()是如果存在则调用的钩子方法。如果没有定义这样的方法,该str()函数将退回到合理的默认值。钩子是用来覆盖默认行为的,你不应该假设它们总是被实现。

此外,仅使用str()可调用对象更具可读性。

于 2012-12-11T22:55:50.533 回答
4

打字更少,代码更容易阅读。

于 2012-12-11T22:56:05.407 回答