格式化字符串

实例的字符串显示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y

def __repr__(self):
return f'({self.x}, {self.y})'


def __str__(self):
return f'Pair({self.x=}, {self.y=})'

p = Pair(3, 4)
print(p)

1
2
3
4
5
6
7
8
from dataclasses import dataclass

@dataclass
class Pair:
x:int
y:int = 0 # y 默认值为0
p = Pair(3, 4)
print(p)

对象自定义格式化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
_formats = {
'ymd': '{d.year}-{d.month}-{d.day}',
'mdy': '{d.month}/{d.day}/{d.year}',
'dmy': '{d.day}/{d.month}/{d.year}'
}


class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day

def __format__(self, code):
if code == '':
code = 'ymd'
fmt = _formats[code]
return fmt.format(d=self)


d = Date(2012, 12, 21)
print(d)
print(format(d, 'mdy'))
print('The date is {:ymd}'.format(d))
print('The date is {:mdy}'.format(d))

修改后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from dataclasses import dataclass
_formats = {
'ymd': '{d.year}-{d.month}-{d.day}',
'mdy': '{d.month}/{d.day}/{d.year}',
'dmy': '{d.day}/{d.month}/{d.year}'
}

@dataclass
class Date:
year:int
month:int
day:int

def __format__(self, code):
if code == '':
code = 'ymd'
fmt = _formats[code]
return fmt.format(d=self)


a = Date(2012, 12, 21)
print(a)
print(format(a, 'mdy'))
print('The date is {:ymd}'.format(a))
print('The date is {:mdy}'.format(a))