一、实例对象的字符串表示
修改实例对象的 __str__()
和 __repr__()
方法可以改变该实例生成的字符串输出。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Pair({0.x!r}, {0.y!r})'.format(self)
def __str__(self):
return '({0.x!s}, {0.y!s})'.format(self)
# test
3, 4) p = Pair(
p
Pair(3, 4) # __repr__() output
# __str__() output print(p)
(3, 4)
二、自定义字符串格式化
通过定义实例的 __format__
方法,可以配置实例对象接受字符串格式化操作时的表现(即定义被 format
函数调用的方式与调用后的输出结果)。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
26
27_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(format(d))
print(format(d, 'mdy'))
print('The date is {:ymd}'.format(d))
# => 2012-12-21
# => 12/21/2012
# => The date is 2012-12-21
三、使对象支持 Context-Management 协议
为了使某个对象支持 Context-Management(即 with
语句),需要在类中实现 __enter__()
和 __exit__()
方法。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
26
27
28
29
30
31from socket import socket, AF_INET, SOCK_STREAM
class LazyConnection:
def __init__(self, address, family=AF_INET, type=SOCK_STREAM):
self.address = address
self.family = family
self.type = type
self.sock = None
def __enter__(self):
if self.sock is not None:
raise RuntimeError('Already connected')
self.sock = socket(self.family, self.type)
self.sock.connect(self.address)
return self.sock
def __exit__(self, exc_ty, exc_val, tb):
self.sock.close()
self.sock = None
# test code
from functools import partial
conn = LazyConnection(('www.python.org', 80))
with conn as s:
s.send(b'GET /index.htm HTTP/1.0\r\n')
s.send(b'Host: www.python.org\r\n')
s.send(b'\r\n')
resp = b''.join(iter(partial(s.recv, 8192), b''))
print(resp)
四、创建自定义属性
有些时候,在设置或者获取某个实例属性的值时,需要对其添加额外的操作,比如类型检查或者属性值的合法性检查等。
这类需求可以使用 @property
装饰器来完成。
1 | class Person: |
PS:和 Java 等语言的使用习惯不同,Python 的 Property
属性应该只用在访问属性时需要对其进行额外处理的情况下。并不是所有对属性的访问都需要由 getter
或 setter
处理。
Property
还可以用来创建按需计算的属性。即属性值并非预先存放在某个地方,而是在访问它时实时地计算并返回。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
c = Circle(4.0)
print(c.radius) # => 4.0
print(c.area) # => 50.26548245743669
print(c.perimeter) # => 25.132741228718345
五、简化数据结构的初始化
有些时候,程序中会包含很多需要用类去定义的数据结构,导致出现类似下面的代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Stock:
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
上述多个数据结构(Stock
、Point
、Circle
)都是通过 __init__
方法进行初始化的。实际上可以先定义一个基类,在其中抽象出 __init__
方法的逻辑,使其可以作为一个通用的方法简化重复的初始化操作。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
26
27
28
29class Structure:
# Class variable that specifies expected fields
_fields = []
def __init__(self, *args, **kwargs):
if len(args) != len(self._fields):
raise TypeError('Expected {} arguments'.format(len(self._fields)))
# Set the arguments
for name, value in zip(self._fields, args):
setattr(self, name, value)
# Set the additional arguments (if any)
extra_args = kwargs.keys() - self._fields
for name in extra_args:
setattr(self, name, kwargs.pop(name))
if kwargs:
raise TypeError('Duplicate values for {}'.format(','.join(kwargs)))
# Example use
if __name__ == '__main__':
class Stock(Structure):
_fields = ['name', 'shares', 'price']
s1 = Stock('ACME', 50, 91.1)
s2 = Stock('ACME', 50, 91.1, date='8/2/2012')
print(s1.shares)
# => 50
print(s2.date)
# => 8/2/2012
六、定义额外的构造器
类方法可以作为除 __init__()
方法以外的,另一个用来创建类实例的构造方法。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24import time
class Date:
# Primary constructor
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
# Alternate constructor
def today(cls):
t = time.localtime()
return cls(t.tm_year, t.tm_mon, t.tm_mday)
def __repr__(self):
return f'{self.year}-{self.month}-{self.day}'
a = Date(2019, 12, 23)
print(a) # => 2019-12-23
b = Date.today()
print(b) # => 2019-12-23
七、通过 Mixin 扩展类
1 | # mixins.py |
测试代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22from mixins import *
class LoggedDict(LoggedMappingMixin, dict):
pass
...
d = LoggedDict()
'x'] = 23 d[
Setting x = 23
'x'] d[
Getting x
23
del d['x']
Deleting x
>>>
class SetOnceStringDict(StringKeysMappingMixin, SetOnceMappingMixin, dict):
pass
...
d2 = SetOnceStringDict()
'x'] = 23 d2[
'x'] = 10 d2[
KeyError: 'x already set'
3] = 42 d2[
TypeError: keys must be strings
八、使类支持比较运算符
1 | from functools import total_ordering |