[英]Django complicated string representation of a model object (def __str__(self):)
[英]Python's join() won't join the string representation (__str__) of my object
我不确定我在这里做错了什么:
>>> class Stringy(object):
... def __str__(self):
... return "taco"
... def __repr__(self):
... return "taco"
...
>>> lunch = Stringy()
>>> lunch
taco
>>> str(lunch)
'taco'
>>> '-'.join(('carnitas',lunch))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 1: expected string, Stringy found
鉴于我在Stringy对象中包含了__str__()
方法,不应该将join()
看作午餐作为字符串吗?
不,你必须将它转换为str自己
'-'.join(('carnitas',str(lunch)))
如果你必须为整个项目序列做这件事
'-'.join(str(x) for x in seq)
要么
'-'.join(map(str, seq))
对于你的特殊情况,你可以写
'carnitas-'+str(lunch)
''.join
不会在它加入的序列中调用__str__
。 __str__
每个对象都有一个__str__
(它只是从object
继承),因此如果join
这种方式工作,它将连接任何序列(在字符串化之后) - 通常是奇怪的效果。 最好让用户在保证时明确地调用str
(毕竟,“显式优于隐式”是“The Zen of Python”中的一个格言)。
如果你想“成为”一个字符串,你可以继承str
或unicode
。 否则,将需要显式str
调用以使您的类型的实例“成为”字符串。
str.join
的调用签名是:
S.join(sequence) -> string
Return a string which is the concatenation of the strings in the
sequence. The separator between elements is S.
请注意, sequence
应该是一个字符串序列。 很多对象都有__str__
方法,但并非所有对象(如Stringy
)都是str
的实例。
当然,修复很简单:
'-'.join(('carnitas',str(lunch)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.