Python中class的内置函数__str__


在python中,如果我们定义一个class:
class Friend():
def __init__(self, name):
self.name = name

if __name__ == '__main__':
friend = Friend('Liang')
print friend
那么在申明一个实例对象friend并打印其信息时,python返回的是它的存储地址
<__main__ .Friend instance at 0x7ff3596c>
到底应该怎么做才能打印出一个对象的有感内容呢?可以通过__str__函数
class Friend():
def __init__(self, name):
self.name = name

def __str__(self):
return "Friend : %s" % self.name

if __name__ == '__main__':
friend = Friend('Liang')
print friend
此时,打印出的内容为:
Friend name : Liang
显然的,内置函数带来了这种便利,理所当然要有所约束,那就是这个方法只能返回str,并且只能有self这一个参数,其他的,自行发挥。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章