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))
    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM