首页 > 编程语言 > 详细

python 重写__repr__与__str__函数

时间:2020-07-12 17:03:16      阅读:116      评论:0      收藏:0      [点我收藏+]

python 重写__repr__与__str__函数

str():在调用print打印对象时自动调用,是给用户用的,是一个描述对象的方法。
repr():是给机器用的,在Python解释器里面直接敲对象名在回车后调用的方法
注意:在没有str时,且有repr,str = repr

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 "%s-%d-%d-%d" % (self.name, self.age, self.height, self.weight)


per = Person("hanmeimei", 20, 170, 55)
#print(per.name, per.age, per.height, per.weight)
print(per)

python 重写__repr__与__str__函数

原文:https://www.cnblogs.com/bailongcaptain/p/13288454.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!