Python中类的使用(4__str__()简单了解)


重新:将函数重新写一遍
__repr__:是给机器用的,在Python解释器里面直接敲对象名在回车后调用的方法
__str__:在调用print打印对象自动调用,是一个给用户用的描述对象方法
注意:如果没有__str__且有__repr__,则__str__=__repr__.

优点:当一个对象的属性值很多,并且需要打印,__str__简化代码
'''
class Person(object):
def __init__(self,name,age,height,weight):
self.name=name
self.age=age
self.height=height
self.weight=weight
def __str__(self):
# return"这是str"#return返回值,避免Print中无值出错
return "%s %d %d %d"%(self.name,self.age,self.height,
self.weight)
per1=Person("lili",20,175,50)
per2=Person("lilie",10,105,30)
per3=Person("tom",45,165,62)
#print( per1,"\n",per2,"\n",per3)#换行符会有缩进,不能对齐
print(per1)
print(per2)
print(per3)
posted @ 2019-03-04 16:05  飞飞阿  阅读(486)  评论(0编辑  收藏  举报