通过format学习,python的内部方法是面象对象的-python面向对象

1、常用的形式

s ="{0} {0} qqq {0} xxx {1}".format('dog','cat')
print(s)

结果:dog dog qqq dog xxx cat

 

2、进阶形式

class Date:
  def __init__(self,year,month,day):
    self.year = year
    self.month = month
    self.day = day

d1 = Date(2018,3,9)
s = "{0} - {0} - {0}".format(d1)
print(s)
s = "{0.year}-{0.month}-{0.day}".format(d1)
print(s)

 

3、进阶形式

format_dic={
  'ymd':'{0.year}{0.month}{0.day}',
  'y-m-d':'{0.year}-{0.month}-{0.day}',
  'y/m/d':'{0.year}/{0.month}/{0.day}',
  'y m d':'{0.year} {0.month} {0.day}',
}
class Date:
  def __init__(self,year,month,day):
    self.year = year
    self.month = month
    self.day = day

  def __format__(self, format_spec):
    if not format_spec:
      format_spec = 'ymd'
      s = format_dic[format_spec]
    return s.format(self)

d = Date1(2018,8,8)
s = format(d,'y/m/d')
print(s)

结论:format(key) ---------------------key.__format__(self.format_spec)

posted @ 2018-03-09 17:24  Python信仰  阅读(229)  评论(0编辑  收藏  举报