如果我这样做:
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
关于python - 如何在Python中为类设置字符串渲染方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9799493/