2011-10-27 66 views
1

我想扩展我的对象的__str__()方法。该str(obj)目前写着:扩展__str __()而不是替换它

<mymodule.Test object at 0x2b1f5098f2d0> 

我喜欢的地址作为唯一的标识符,但我想添加一些属性。在保留地址部分的同时扩展此最佳方式是什么?我想看起来像这样:

<mymodule.Test object at 0x2b1f5098f2d: name=foo, isValid=true> 

我不'看到任何存储地址的属性。我使用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) 
+1

首先,不要使用这样一个过时的python版本。除此之外,你正在尝试做的是'__repr__'。 – ThiefMaster

回答

5

您可以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))) 

测试 有:

test = Test() 
test.name = "foo" 
test.isValid = True 
print repr(test) 
print str(test) 
print test 

您可以轻松地做同样的事情在旧版本的Python的使用字符串格式化像操作"%s"而不是更清晰的str.format()语法。如果要使用str.format(),则还可以在模板中使用{1:#x},并将参数1从hex(id(self))更改为id(self),然后使用其内置的十六进制格式化功能。

+0

其余的呢?我看到obj .__ class __.__ name__将返回Test,但模块名称又如何? – shadowland

+0

已编辑为有完整答案。 –

+0

这样做。我只是不得不按照你的建议使用%s。 – shadowland

1
class Mine(object): 
    def __str__(self): 
     return object.__str__(self) + " own attributes..." 
+1

这不会产生他想要的输出。他希望这一切都在他的例子中的尖括号中。这将返回它自己的一组尖括号中的原始数据,并将它的属性添加到它们的“外部”。 –