Python基本特殊方法之__format__

__format__()方法__format__()传参方法:someobject.__format__(specification)specification为指定格式,当应用程序中出现&quo

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

全栈程序员社区此处内容已经被作者隐藏,请输入验证码查看内容
验证码:
请关注本站微信公众号,回复“验证码”,获取验证码。在微信里搜索“全栈程序员社区”或者“www_javaforall_cn”或者微信扫描右侧二维码都可以关注本站微信公众号。

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

Python基本特殊方法之__format__

  例:格式化对象中的集合

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

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/120192.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号