example-code-2e/06-obj-ref/cheese.py

29 lines
599 B
Python
Raw Normal View History

2020-02-19 04:12:02 +01:00
"""
>>> import weakref
>>> stock = weakref.WeakValueDictionary()
>>> catalog = [Cheese('Red Leicester'), Cheese('Tilsit'),
... Cheese('Brie'), Cheese('Parmesan')]
2020-02-19 04:12:02 +01:00
...
>>> for cheese in catalog:
... stock[cheese.kind] = cheese
...
>>> sorted(stock.keys())
['Brie', 'Parmesan', 'Red Leicester', 'Tilsit']
>>> del catalog
>>> sorted(stock.keys())
['Parmesan']
>>> del cheese
>>> sorted(stock.keys())
[]
"""
# tag::CHEESE_CLASS[]
class Cheese:
def __init__(self, kind):
self.kind = kind
def __repr__(self):
return f'Cheese({self.kind!r})'
2020-02-19 04:12:02 +01:00
# end::CHEESE_CLASS[]