Cookie Jar

Source: Sesame Street
假设 you’d like to 实现一个 cookie jar in which to store cookies. In 名为 jar.py, 实现一个 class called Jar with these methods:
-
__init__should initialize a cookie jar with the givencapacity, which represents the maximum number of cookies that can fit in the cookie jar. Ifcapacityis not a non-negativeint, though,__init__should instead raise aValueError(viaraise ValueError). -
__str__should return astrwith n🍪, where n is the number of cookies in the cookie jar. For instance, if there are 3 cookies in the cookie jar, thenstrshould return"🍪🍪🍪" -
depositshould addncookies to the cookie jar. If adding that many would exceed the cookie jar’s capacity, though,depositshould instead raise aValueError. -
withdrawshould removencookies from the cookie jar. Nom nom nom. If there aren’t that many cookies in the cookie jar, though,withdrawshould instead raise aValueError. -
capacityshould return the cookie jar’s capacity. -
sizeshould return the number of cookies actually in the cookie jar.
Structure your class per the below. You可能不 alter these methods’ parameters, but you 五月 add your own methods.
class Jar:
def __init__(self, capacity=12):
...
def __str__(self):
...
def deposit(self, n):
...
def withdraw(self, n):
...
@property
def capacity(self):
...
@property
def size(self):
...
演示
You’re 欢迎, but not 必需, to 实现一个 main function in which to test your class, so this is all we can demo!

Source: Sesame Street
Before You Begin
- Log into cs50.dev using your GitHub account.
- Click inside the terminal window and execute
cd. - Execute
wget https://cdn.cs50.net/2022/fall/实验s/6/jar.zipfollowed by Enter in order to 下载 a zip calledjar.zipin your codespace. Take care not to overlook the space betweenwgetand the following URL, or any other character for that matter! - Now execute
unzip jar.zipto create 的文件夹中名为jar. - You 不再 need the ZIP file, so you can execute
rm jar.zipand respond with “y” followed by Enter at the prompt.
如何测试
Here’s how to test your code manually:
- Define a
mainfunction in yourjar.pyfile, wherein you 创建一个 new instance ofJarwithjar = Jar(). Test thisjarhas the capacity it should by callingprint(str(jar.capacity)). Be sure your program callsmainat the bottom of the file, as viamain(). - Test that your
__str__function works as intended by callingprint(str(jar)). - Try calling
jar.deposit(2)to deposit two cookies. Callingprint(str(jar))should now show you the same number of cookies you’ve deposited. - Try calling
jar.withdraw(1)to withdraw one cookie. Callingprint(str(jar))should now show you one fewer cookie than you had before. - Try experimenting with depositing and withdrawing various amounts of cookies. Are you unable to withdraw past the jar’s size? Are you unable to deposit past the jar’s capacity?
No check50 for this one!
如何提交
No need to 提交! This is a 练习题.