python __str__,__repr__

八 __str__,__repr__,__format__

class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    
    # 相当于java的toString()
    def __str__(self):
        return ('name:%s,age:%s'%(self.name,self.age))

    def __repr__(self):
        return ('name1:%s,age1:%s'%(self.name,self.age))

f = Foo('long',20)
print(f) # f.__str__()
print(f)  # f.__repr__()

# 如果__str__没有被定义,那么就会使用__repr__来代替输出
# 注意:这俩方法的返回值必须是字符串,否则抛出异常

__format__ 自定义格式化

format_dict = {
    'ymd':'{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):
        print('执行了__format__:',format_spec)
        if not format_spec or format_spec not in format_dict:
            format_spec = 'ymd'
        fm = format_dict[format_spec]
        return fm.format(self)  # '{0.year}{0.month}{0.day}'.format(d1)  # 2019822

d1 = Date(2019,8,22)

x = format(d1,'y-m-d')  # d1__format__()
print(x)   # 2019-8-22

# x = '{0.year}{0.month}{0.day}'.format(d1)  # 2019822
# print(x)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值