June 2017
Beginner
352 pages
8h 39m
English
The with-statement construct can be used with any type of object which implements the context manager protocol. We're not going to show you how to implement a context-manager is this book – for that you'll need to refer to The Python Journeyman – but we will show you a simple way to make your own classes usable in a with statement. Put this code into a the module fridge.py:
# fridge.py"""Demonstrate raiding a refrigerator."""class RefrigeratorRaider: """Raid a refrigerator.""" def open(self): print("Open fridge door.") def take(self, food): print("Finding {}...".format(food)) if food == 'deep fried pizza': raise RuntimeError("Health warning!") print("Taking {}".format(food)) def close(self): print("Close fridge door.") def ...Read now
Unlock full access