【1.129】__format__函数

#看看 format 的功能
print("I LOVE {0},{1}".format("LUCY","LILY","MEIMEI"))
#I LOVE LUCY,LILY

ymd_dict={
    "ymd":"{obj.year}{obj.month}{obj.day}",
    "dmy":"{obj.day}/{obj.month}/{obj.year}",
    "y:m:d":"{obj.year}:{obj.month}:{obj.day}"
}

class Foo:
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day
    def __format__(self, format_spec):
        if format_spec not in ymd_dict or not format_spec:
            format_spec = "ymd"
        data_gs=ymd_dict[format_spec]
        return data_gs.format(obj=self)

date1= Foo(2016,7,3)
print(date1.__dict__)  
#{'year': 2016, 'month': 7, 'day': 3}
print(date1)
# <__main__.Foo object at 0x0000000001EA6898>
print(format(date1))
# 201673
print(format(date1,"y:m:d"))
# 2016:7:3
print(format(date1,"dmy"))
# 3/7/2016

 

posted @ 2019-07-03 15:13  科学小怪癖  阅读(104)  评论(0)    收藏  举报