python的魔术方法 __format__

__format__()方法

  __format__()传参方法:someobject.__format__(specification)

  specification为指定格式,当应用程序中出现"{0:specification}".format(someobject)或format(someobject, specification)时,会默认以这种方式调用

  当specification为" "时,一种合理的返回值是return str(self),这为各种对象的字符串表示形式提供了明确的一致性

  注意,"{0!s}".format()和"{0!r}".format()并不会调用__format__()方法,他们会直接调用__str__()或者__repr__()

  例:自定义我们自己的__format__()格式

复制代码
#coding=utf-8

class formatest:
    def __init__(self, name, age):
        self.name,self.age = name, age

    def __format__(self,specification):
        if specification == "":
            return str(self)

        strformat = specification.replace("%s",self.name).replace("%r",self.age)
        return strformat

if __name__ == "__main__":
    people = formatest("zhanglin", "31")
    print ("{}".format(people))
    print ("{0:%s-%r}".format(people))
    print (format(people, "%s-%r"))
    
复制代码

  例:格式化对象中的集合

复制代码
#coding=utf-8

class people:
    def __init__(self, name, age):
        self.name,self.age = name, age

    def __format__(self,specification):
        if specification == "":
            return str(self)

        strformat = specification.replace("%s",self.name).replace("%r",self.age)
        return strformat

class hand:
    def __init__(self, *people):
        self.peoples = []
        self.peoples= list(people)
    def __format__(self, specification):
        if specification == "":
            return str(self)        
        return ",".join("{:{fs}}".format(c, fs=specification) for c in self.peoples)
  
if __name__ == "__main__":
    handobj = hand(people("zhangsan", "18"), people("lisi", "28"), people("zhanglin", "38"))
    print ("{:%s-%r}".format(handobj))
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值