|
9 | 9 | >>> name, weight, _ = rex # <3> |
10 | 10 | >>> name, weight |
11 | 11 | ('Rex', 30) |
12 | | - >>> "{2}'s dog weights {1}kg".format(*rex) |
| 12 | + >>> "{2}'s dog weights {1}kg".format(*rex) # <4> |
13 | 13 | "Bob's dog weights 30kg" |
14 | | - >>> rex.weight = 32 # <4> |
| 14 | + >>> rex.weight = 32 # <5> |
15 | 15 | >>> rex |
16 | 16 | Dog(name='Rex', weight=32, owner='Bob') |
17 | | - >>> Dog.__mro__ # <5> |
| 17 | + >>> Dog.__mro__ # <6> |
18 | 18 | (<class 'factories.Dog'>, <class 'object'>) |
19 | 19 |
|
20 | 20 | # END RECORD_FACTORY_DEMO |
21 | 21 | """ |
22 | 22 |
|
23 | 23 | # BEGIN RECORD_FACTORY |
24 | 24 | def record_factory(cls_name, field_names): |
25 | | - if isinstance(field_names, str): # <1> |
| 25 | + if isinstance(field_names, str): |
26 | 26 | field_names = field_names.replace(',', ' ').split() |
27 | | - __slots__ = tuple(field_names) |
| 27 | + field_names = tuple(field_names) # <1> |
28 | 28 |
|
29 | | - def __init__(self, *args, **kwargs): |
| 29 | + def __init__(self, *args, **kwargs): # <2> |
30 | 30 | attrs = dict(zip(self.__slots__, args)) |
31 | 31 | attrs.update(kwargs) |
32 | 32 | for name, value in attrs.items(): |
33 | 33 | setattr(self, name, value) |
34 | 34 |
|
35 | | - def __iter__(self): |
| 35 | + def __iter__(self): # <3> |
36 | 36 | for name in self.__slots__: |
37 | 37 | yield getattr(self, name) |
38 | 38 |
|
39 | | - def __repr__(self): |
| 39 | + def __repr__(self): # <4> |
40 | 40 | values = ', '.join('{}={!r}'.format(*i) for i |
41 | 41 | in zip(self.__slots__, self)) |
42 | 42 | return '{}({})'.format(self.__class__.__name__, values) |
43 | 43 |
|
44 | | - cls_attrs = dict(__slots__ = __slots__, |
45 | | - __init__ = __init__, |
46 | | - __iter__ = __iter__, |
47 | | - __repr__ = __repr__) |
| 44 | + cls_attrs = dict(__slots__ = field_names, # <5> |
| 45 | + __init__ = __init__, |
| 46 | + __iter__ = __iter__, |
| 47 | + __repr__ = __repr__) |
48 | 48 |
|
49 | | - return type(cls_name, (object,), cls_attrs) |
| 49 | + return type(cls_name, (object,), cls_attrs) # <6> |
50 | 50 | # END RECORD_FACTORY |
0 commit comments