Python Cookbook —— 类与对象

一、实例对象的字符串表示

修改实例对象的 __str__()__repr__() 方法可以改变该实例生成的字符串输出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class 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
>>> p = Pair(3, 4)
>>> p
Pair(3, 4) # __repr__() output
>>> print(p) # __str__() output
(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
31
from 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
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
class Person:
def __init__(self, first_name):
self._first_name = first_name

# Getter function
@property
def first_name(self):
return self._first_name

# Setter function
@first_name.setter
def first_name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._first_name = value

# Deleter function(optional)
@first_name.deleter
def first_name(self):
raise AttributeError("Can't delete attribute")

# test code
a = Person('Guido')
print(a.first_name) # => Guido
a.first_name = 'Linus'
print(a.first_name) # => Linus
a.first_name = 42 # => TypeError: Expected a string
del a.first_name # => AttributeError: can't delete attribute

PS:和 Java 等语言的使用习惯不同,Python 的 Property 属性应该只用在访问属性时需要对其进行额外处理的情况下。并不是所有对属性的访问都需要由 gettersetter 处理。

Property 还可以用来创建按需计算的属性。即属性值并非预先存放在某个地方,而是在访问它时实时地计算并返回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import math

class Circle:
def __init__(self, radius):
self.radius = radius

@property
def area(self):
return math.pi * self.radius ** 2

@property
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
19
class 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

上述多个数据结构(StockPointCircle)都是通过 __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
29
class 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
24
import time

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

# Alternate constructor
@classmethod
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
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
31
32
33
34
35
36
37
38
39
40
41
42
# mixins.py
class LoggedMappingMixin:
'''
Add logging to get/set/delete operations for debugging.
'''
__slots__ = ()

def __getitem__(self, key):
print(f'Getting {key}')
return super().__getitem__(key)

def __setitem__(self, key, value):
print(f'Setting {key} = {value}')
return super().__setitem__(key, value)

def __delitem__(self, key):
print(f'Deleting {key}')
return super().__delitem__(key)


class SetOnceMappingMixin:
'''
Only allow a key to be set once.
'''
__slots__ = ()

def __setitem__(self, key, value):
if key in self:
raise KeyError(f'{key} already set')
return super().__setitem__(key, value)


class StringKeysMappingMixin:
'''
Restrict keys to strings only.
'''
__slots__ = ()

def __setitem__(self, key, value):
if not isinstance(key, str):
raise TypeError('keys must be strings')
return super().__setitem__(key, value)

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> from mixins import *
>>> class LoggedDict(LoggedMappingMixin, dict):
... pass
...
>>> d = LoggedDict()
>>> d['x'] = 23
Setting x = 23
>>> d['x']
Getting x
23
>>> del d['x']
Deleting x
>>>
>>> class SetOnceStringDict(StringKeysMappingMixin, SetOnceMappingMixin, dict):
... pass
...
>>> d2 = SetOnceStringDict()
>>> d2['x'] = 23
>>> d2['x'] = 10
KeyError: 'x already set'
>>> d2[3] = 42
TypeError: keys must be strings

八、使类支持比较运算符

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from functools import total_ordering

class Room:
def __init__(self, name, length, width):
self.name = name
self.length = length
self.width = width
self.square_feet = self.length * self.width


@total_ordering
class House:
def __init__(self, name, style):
self.name = name
self.style = style
self.rooms = list()

@property
def living_space_footage(self):
return sum(r.square_feet for r in self.rooms)

def add_room(self, room):
self.rooms.append(room)

def __str__(self):
return f'{self.name}: {self.living_space_footage} square foot {self.style}'

def __eq__(self, other):
return self.living_space_footage == other.living_space_footage

def __lt__(self, other):
return self.living_space_footage < other.living_space_footage


# Build a few houses, and add rooms to them
h1 = House('h1', 'Cape')
h1.add_room(Room('Master Bedroom', 14, 21))
h1.add_room(Room('Living Room', 18, 20))
h1.add_room(Room('Kitchen', 12, 16))
h1.add_room(Room('Office', 12, 12))

h2 = House('h2', 'Ranch')
h2.add_room(Room('Master Bedroom', 14, 21))
h2.add_room(Room('Living Room', 18, 20))
h2.add_room(Room('Kitchen', 12, 16))

h3 = House('h3', 'Split')
h3.add_room(Room('Master Bedroom', 14, 21))
h3.add_room(Room('Living Room', 18, 20))
h3.add_room(Room('Office', 12, 16))
h3.add_room(Room('Kitchen', 15, 17))

houses = [h1, h2, h3]

print('Is h1 bigger than h2?', h1 > h2) # => True
print('Is h2 smaller than h3?', h2 < h3) # => True
print('Is h2 greater than or equal to h1?', h2 >= h1) # => False
print('Which one is biggest?', max(houses)) # => h3: 1101 square foot Split
print('Which is smallest?', min(houses)) # => h2: 846 square foot Ranch

参考资料

Python Cookbook, 3rd Edition