__str__ __repr__ 与 __format__

# __str__ __repr__ 与 __format__
class Foo:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def __str__(self):
        return '改变了对象的字符串方式,默认为对象的内存地址'

    def __repr__(self):
        return '在控制台输出时(或没有__str__)的显示方式'

    # __str__ 与 __repr__ 只能return字符串类型

    def __format__(self, format_spec):
        if not format_spec or format_spec not in format_dic:     # 此处判断用户是否传空参数或字典中没有的参数,并指定一个值
            format_spec = 'm-d-y'

        fm = format_dic[format_spec]    # 从字典format_dic中找到相应的格式
        return fm.format(self)  # 返回显示的格式


f1 = Foo(2018, 5, 8)
print(f1)  # 相当于 str(f1) -> f1.__str__ 这样执行

# 对于__str__ 和 __repr__ 都存在的话,print会先找__str__,如果没有__str__就执行__repr

# 定义format显示方式的字典
format_dic = {
    'y-m-d': '{0.year}-{0.month}-{0.day}',
    'm-d-y': '{0.month}-{0.day}-{0.year}'
}
print(format(f1))  # 当使用format方法时会调用__format__方法,并按我们定义的显示方式显示

 

posted @ 2018-08-13 20:00  四十不惑的编程之路  阅读(163)  评论(0编辑  收藏  举报