接上一篇,内置方法续集:

  六、__str__,__repr__ 和 __format__

    1、作用:__str__,__repr__ 改变对象的字符串显示

        __format__ 自定制格式化字符串

    2、示例:

#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# write by congcong

format_dict={
    'way1':'{obj.name}-{obj.addr}-{obj.type}',#学校名-学校地址-学校类型
    'way2':'{obj.type}:{obj.name}:{obj.addr}',#学校类型:学校名:学校地址
    'way3':'{obj.type}/{obj.addr}/{obj.name}',#学校类型/学校地址/学校名
}
class School:
    def __init__(self,name,addr,type):
        self.name = name
        self.addr = addr
        self.type = type
    def __repr__(self):
        return 'School(%s,%s)'%(self.name,self.addr)
    def __str__(self):
        return '(%s,%s)'%(self.name,self.addr)
    def __format__(self, format_spec):
        if not format_spec or format_spec not in format_dict:
            format_spec = 'way1'
        fmt =format_dict[format_spec]
        return fmt.format(obj=self)

s1 = School('lufei','上海','培训机构')

print('from repr:',repr(s1)) # from repr: School(lufei,上海)
print('from str:',str(s1)) #  from str: (lufei,上海)
print(s1) # (lufei,上海)

print(format(s1,'way2'))# 培训机构:lufei:上海
print(format(s1,'way3')) # 培训机构/上海/lufei
print(format(s1,'abcdef')) # 培训机构/上海/lufei
'''
str函数或者print函数--->obj.__str__()
repr或者交互式解释器--->obj.__repr__()
如果__str__没有被定义,那么就会使用__repr__来代替输出
'''
View Code

相关文章:

  • 2022-12-23
  • 2021-06-19
  • 2022-12-23
  • 2022-12-23
  • 2021-08-27
  • 2021-08-21
  • 2021-08-13
猜你喜欢
  • 2021-06-16
  • 2021-06-05
  • 2021-08-17
  • 2021-10-02
  • 2022-12-23
  • 2021-06-01
  • 2021-11-20
相关资源
相似解决方案