发现给对象定义 __str__(self) 方法,之后打印包含这类对象的list,打印出来的是对象的内存地址,
会出现这样的打印结果:[<__main__.node object at 0x7f572f860860>, <__main__.node object at 0x7f572f860dd8>]
在网上搜到了直接打印对象属性内容的方法:将 __str__(self) 改为 __repr__(self)
例子:
class Car: #
def __init__( self, name, price ):
self.name = name
self.price = price
#def __str__( self ): # 不使用__str__,改用__repr__
def __repr__( self ):
return "%s - %d" % ( self.name, self.price )
def __cmp__( self, other ):
if self.name > other.name:
return 1
elif self.name == other.name:
return 0
else:
return -1
def __iter__( self ):
return self
#
#
if __name__ == '__main__':
carList = []
c1 = Car( "byd", 15 )
c2 = Car( "audi", 10 )
carList.append( c1 )
carList.append( c2 )
print( carList )
打印结果是 [byd - 15, audi- 10]