|
| 1 | +""" |
| 2 | +
|
| 3 | +A line item for a bulk food order has description, weight and price fields:: |
| 4 | +
|
| 5 | + >>> raisins = LineItem('Golden raisins', 10, 6.95) |
| 6 | + >>> raisins.weight, raisins.description, raisins.price |
| 7 | + (10, 'Golden raisins', 6.95) |
| 8 | +
|
| 9 | +A ``subtotal`` method gives the total price for that line item:: |
| 10 | +
|
| 11 | + >>> raisins.subtotal() |
| 12 | + 69.5 |
| 13 | +
|
| 14 | +The weight of a ``LineItem`` must be greater than 0:: |
| 15 | +
|
| 16 | + >>> raisins.weight = -20 |
| 17 | + Traceback (most recent call last): |
| 18 | + ... |
| 19 | + ValueError: value must be > 0 |
| 20 | +
|
| 21 | +No change was made:: |
| 22 | +
|
| 23 | + >>> raisins.weight |
| 24 | + 10 |
| 25 | +
|
| 26 | +The value of the attributes managed by the descriptors are stored in |
| 27 | +alternate attributes, created by the descriptors in each ``LineItem`` |
| 28 | +instance:: |
| 29 | +
|
| 30 | + >>> raisins = LineItem('Golden raisins', 10, 6.95) |
| 31 | + >>> dir(raisins) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE |
| 32 | + ['_Quantity_0', '_Quantity_1', '__class__', ... |
| 33 | + 'description', 'price', 'subtotal', 'weight'] |
| 34 | + >>> raisins._Quantity_0 |
| 35 | + 10 |
| 36 | + >>> raisins._Quantity_1 |
| 37 | + 6.95 |
| 38 | +
|
| 39 | +If the descriptor is accessed in the class, the descriptor object is |
| 40 | +returned: |
| 41 | +
|
| 42 | + >>> LineItem.price # doctest: +ELLIPSIS |
| 43 | + <bulkfood_v4b.Quantity object at 0x...> |
| 44 | + >>> br_nuts = LineItem('Brazil nuts', 10, 34.95) |
| 45 | + >>> br_nuts.price |
| 46 | + 34.95 |
| 47 | +
|
| 48 | +""" |
| 49 | + |
| 50 | + |
| 51 | +# BEGIN LINEITEM_V4B |
| 52 | +class Quantity: |
| 53 | + __counter = 0 |
| 54 | + |
| 55 | + def __init__(self): |
| 56 | + cls = self.__class__ |
| 57 | + prefix = cls.__name__ |
| 58 | + index = cls.__counter |
| 59 | + self.storage_name = '_{}_{}'.format(prefix, index) |
| 60 | + cls.__counter += 1 |
| 61 | + |
| 62 | + def __get__(self, instance, owner): |
| 63 | + if instance is None: |
| 64 | + return self # <1> |
| 65 | + else: |
| 66 | + return getattr(instance, self.storage_name) # <2> |
| 67 | + |
| 68 | + def __set__(self, instance, value): |
| 69 | + if value > 0: |
| 70 | + setattr(instance, self.storage_name, value) |
| 71 | + else: |
| 72 | + raise ValueError('value must be > 0') |
| 73 | +# END LINEITEM_V4B |
| 74 | + |
| 75 | + |
| 76 | +class LineItem: |
| 77 | + weight = Quantity() |
| 78 | + price = Quantity() |
| 79 | + |
| 80 | + def __init__(self, description, weight, price): |
| 81 | + self.description = description |
| 82 | + self.weight = weight |
| 83 | + self.price = price |
| 84 | + |
| 85 | + def subtotal(self): |
| 86 | + return self.weight * self.price |
0 commit comments