如果我这样做:
print "The item is:" + str(1) + "."
我会得到:
The item is 1.
但是如果我使用我的类的对象,dbref(这里x是其中之一),并尝试将其字符串化:
print "The item is:" + str(x) + "."
我会得到:
The item is <mufdatatypes.dbref instance at 0xb74a2bec>.
我宁愿它返回一串我自己的设计。我可以在课堂上定义一个能让我这样做的功能吗?
答案 0 :(得分:2)
从the __str__()
method返回一个字符串。像这样:
class SomeClass(object):
def __init__(self, value):
self.value = value
def __str__(self):
return '<SomeClass %s>' % self.value
答案 1 :(得分:1)
定义__str__
方法。
>>> class Spam(object):
... def __str__(self):
... """my custom string representation"""
... return 'spam, spam, spam and eggs'
...
>>> x = Spam()
>>> x
<__main__.Spam object at 0x1519bd0>
>>> print x
spam, spam, spam and eggs
>>> print "The item is:" + str(x) + "."
The item is:spam, spam, spam and eggs.
>>> print "The item is: {}".format(x)
The item is: spam, spam, spam and eggs
编辑 例如,您可能不希望使用__repr__
来覆盖列表中项目的表示或其他容器:
>>> class mystr(str):
... def __repr__(self):
... return str(self)
...
>>> x = ['this list ', 'contains', '3 elements']
>>> print x
['this list ', 'contains', '3 elements']
>>> x = [mystr('this list, also'), mystr('contains'), mystr('3 elements')]
>>> print x
[this list, also, contains, 3 elements]