86 lines
2.6 KiB
Python
86 lines
2.6 KiB
Python
# Create a class that implements a context manager as described in 3.3.9.
|
|
# The context manager should keep track of an array of banana emojis.
|
|
# The class should be able to be used with with: so it adds a banana to the list, and upon exit, removes a banana from the list.
|
|
|
|
# class BananaManager:
|
|
# def __init__(self, bananas):
|
|
# self.bananas = bananas
|
|
|
|
# def __enter__(self):
|
|
# self.bananas.append("🍌")
|
|
# return self.bananas
|
|
|
|
# def __exit__(self, exc_type, exc_value, traceback):
|
|
# self.bananas.pop()
|
|
|
|
# # Usage of the banana manager
|
|
# banana_list = ["🍌", "🍌"]
|
|
# print("Before with statement:", banana_list)
|
|
|
|
# with BananaManager(banana_list) as adding_bananas:
|
|
# print("Inside with statement:", adding_bananas)
|
|
|
|
# print("After with statement:", banana_list)
|
|
|
|
|
|
|
|
# Questions: can you use a with block inside of another with block? (You might have to get creative for this to work.).
|
|
# If you can make that work, how many bananas are in the list?
|
|
|
|
# class BananaManager:
|
|
# def __init__(self, bananas):
|
|
# self.bananas = bananas
|
|
|
|
# def __enter__(self):
|
|
# self.bananas.append("🍌")
|
|
# return self.bananas
|
|
|
|
# def __exit__(self, exc_type, exc_value, traceback):
|
|
# self.bananas.pop()
|
|
|
|
# # Usage of the banana manager
|
|
# banana_list = ["🍌", "🍌"]
|
|
# print("Before with statement:", banana_list)
|
|
|
|
# with BananaManager(banana_list) as adding_bananas:
|
|
# print("Inside first with statement:", adding_bananas)
|
|
|
|
# with BananaManager(adding_bananas) as inside_bananas:
|
|
# print("Inside second with statement:", inside_bananas)
|
|
|
|
# print("After with statement:", banana_list)
|
|
|
|
|
|
|
|
# Another question: can you structure the program so that you can get the class to have more than 0 bananas *outside* of a with block?
|
|
|
|
class BananaManager:
|
|
def __init__(self, bananas):
|
|
self.bananas = bananas
|
|
|
|
def __enter__(self):
|
|
self.bananas.append("🍌")
|
|
return self.bananas
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
self.bananas.pop()
|
|
|
|
def outside_banana(self):
|
|
self.bananas.append("🍌")
|
|
|
|
# Usage of the banana manager
|
|
banana_list = ["🍌", "🍌"]
|
|
print("Before with statement:", banana_list)
|
|
|
|
bananamanager = BananaManager(banana_list)
|
|
bananamanager.outside_banana() # Add a banana outside of a with block
|
|
print("Outside adding a banana:", banana_list)
|
|
|
|
with BananaManager(banana_list) as adding_bananas:
|
|
print("Inside first with statement:", adding_bananas)
|
|
|
|
with BananaManager(adding_bananas) as inside_bananas:
|
|
print("Inside second with statement:", inside_bananas)
|
|
|
|
print("After with statement:", banana_list)
|