2011-10-27 63 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

這不會產生他想要的輸出。他希望這一切都在他的例子中的尖括號中。這將返回它自己的一組尖括號中的原始數據,並將它的屬性添加到它們的「外部」。 –