2012-07-26 26 views
1

我有对象的像字典所以 {'name1':oject_instance_1,'name2':oject_instance_2,'name3':oject_instance_3} 在对象的我的类定义,我已经定义两个__str__() method__repr__()方法如下:上的对象的字典主叫STR

def __str__(self): 
    return('{0} pathway containing {1} genes, with a total sequence length of {2}'.format(self.id, len(self.genes), self.length)) 

def __repr(self): 
    return self.__str__  

万一这一点很重要self.id是一个字符串,self.genes是一个列表,self.length是一个int

问题是,当我去打印这本词典,我得到:

{'pid1003': <Pathway.Pathway instance at 0x10169d680>, 'pid1002': <Pathway.Pathway instance at 0x10169d638>, 'pid1001': <Pathway.Pathway instance at 0x10169d5f0>} 

,但打印在一个循环中像

for v in dict.values(): 
    print(v) 

工作正常。

任何想法为什么? 谢谢!

+3

你的表示方法真的叫'__repr'(没有第二组下划线)? – 2012-07-26 13:33:48

+4

另外,'__repr__'中的代码是不是'return self .__ str __()'?事实上,返回一个方法对象似乎有点奇怪... – mgilson 2012-07-26 13:34:59

+0

那真是令人尴尬。谢谢! :( – 2012-07-26 13:36:55

回答

6

也许你应该执行__repr__而不是__repr

编辑:

而且__repr__应该返回一个字符串,而不是功能。因此,如评论中所述,返回str(self)