如果我做:
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>.
我希望它返回我自己设计的字符串。我可以在课堂上定义一个可以让我做到这一点的功能吗?
最佳答案
从the __str__()
method返回一个字符串。像这样:
class SomeClass(object):
def __init__(self, value):
self.value = value
def __str__(self):
return '<SomeClass %s>' % self.value