首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python相关list类中存类对象

2013-10-11 
python有关list类中存类对象我写了下列代码: 1 #!/usr/bin/python23 class AA:4def __init__(self,aa,bb):

python有关list类中存类对象
我写了下列代码:

 1 #!/usr/bin/python
  2 
  3 class AA:
  4     def __init__(self,aa,bb):
  5         self.aa = aa
  6         self.bb = bb
  7     def __str__(self):
  8         return "#%s,%d#" % (self.aa,self.bb)
  9     def __cmp__(self,other):
 10         if self.aa > other.aa:
 11             return 1
 12         elif self.aa == other.aa:
 13             return 0
 14         else:
 15             return -1
 16     def __iter__(self):
 17         return self
 18 
 19 
 20 if "__main__" == __name__:
 21     mylist = []
 22     aa = AA("we",1)
 23     print aa
 24     mylist.append(aa)
 25     bb = AA("as",10)
 26     mylist.append(bb)
 27     print mylist


打印时却提示  [<__main__.AA instance at 0x7f6893231440>, <__main__.AA instance at 0x7f6893231488>]  怎么打重载方法才能正常打印出list中的数据呢 python?list?print?
[解决办法]
问题是你的“正常”指的是什么,这个就很正常了
你期望输出什么格式?
[解决办法]
object.__repr__(self) 
Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

object.__str__(self) 
Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

[解决办法]
    #~ def __str__(self):
    def __repr__(self):  
        return "#%s,%d#" % (self.aa,self.bb)

热点排行