我想扩展__str__()我的对象的方法.在str(obj)当前读取:
<mymodule.Test object at 0x2b1f5098f2d0>
Run Code Online (Sandbox Code Playgroud)
我喜欢地址作为唯一标识符,但我想添加一些属性.在保持地址部分的同时扩展它的最佳方法是什么?我想看起来像这样:
<mymodule.Test object at 0x2b1f5098f2d: name=foo, isValid=true>
Run Code Online (Sandbox Code Playgroud)
我没有看到任何存储地址的属性.我正在使用python 2.4.3.
编辑:很高兴知道如何使用__repr __()
解决方案(适用于python 2.4.3):
def __repr__(self):
return "<%s.%s object at %s, name=%s, isValid=%s>" % (self.__module__,
self.__class__.__name__, hex(id(self)), self.name, self.isValid)
Run Code Online (Sandbox Code Playgroud)
你可以获得地址id(obj).您可能想要更改__repr__()方法而不是__str__().这是在Python 2.6+中执行此操作的代码:
class Test(object):
def __repr__(self):
repr_template = ("<{0.__class__.__module__}.{0.__class__.__name__}"
" object at {1}: name={0.name}, isValid={0.isValid}>")
return repr_template.format(self, hex(id(self)))
Run Code Online (Sandbox Code Playgroud)
测试:
test = Test()
test.name = "foo"
test.isValid = True
print repr(test)
print str(test)
print test
Run Code Online (Sandbox Code Playgroud)
通过使用字符串格式化操作("%s"而不是更清晰的str.format()语法),您可以轻松地在旧版本的Python中执行相同的操作.如果您打算使用str.format(),您还可以使用其内置的十六进制格式化功能,方法{1:#x}是在模板中使用并将参数1更改hex(id(self))为简单id(self).