python--class:类里面的__format__()方法,自定制格式输出

#下面说一下format函数格式化自定制;、
#以时间显示的格式为例:

class Timeshow:
    def __init__(self, year,mon, day):
        self.year = year
        self.mon = mon
        self.day = day

    format_dic={
        "ymd":"{0.year}{0.mon}{0.day}",
        "y:m:d":"{0.year}:{0.mon}:{0.day}",
        "y-m-d":"{0.year}-{0.mon}-{0.day}",
        "m-d-y":"{0.mon}-{0.day}-{0.year}"
    }

    def __format__(self, format_spec):
        if not format_spec:#这个判断分支,主要是当没有传入format_spec参数时,即给输出默认格式
            return "{0.year}{0.mon}{0.day}".format(self)
        else:
            format_geshi=self.format_dic[format_spec]#如果传了ormat_spec参数,就根据上面定义的format_dic去找到格式,输出
            return format_geshi.format(self)


t=Timeshow(2018,"01","01")
print(t.__format__("y:m:d"))#---->结果:2018:01:01
print(format(t,"m-d-y"))#------->结果:01-01-2018

猜你喜欢

转载自blog.csdn.net/ak739105231/article/details/86613311