# class 类名: —— 定义类。类名习惯用大驼峰(每个单词首字母大写)。 class MenuItem: """Models each Menu Item.""" # __init__ 是构造方法:创建对象时自动调用,用来给这个对象设置初始属性。 # self :指向“正在创建的这个对象”,必须是第一个参数,调用时不用自己传; # name :饮品名(str) # water / milk / coffee:做一杯需要的原料量(数字) # cost :价格(float) # 返回值:不能 return 别的东西,必须返回 None。 def __init__(self, name, water, milk, coffee, cost): # self.xxx = 值 → 把这个值存成“这个对象自己的属性”, # 之后任何方法里都能用 self.xxx 取出来。 # 注意 name 没有加下划线,是公开属性,外部可以直接 item.name 读。 self.name = name self.cost = cost # 把三种原料收进一本字典,方便后面按“原料名”循环处理。 self.ingredients = { "water": water, "milk": milk, "coffee": coffee }
class Menu: """Models the Menu with drinks.""" # 菜单本身不需要外部参数,所以 __init__ 只留 self。 def __init__(self): # self.menu 是一个列表,装 3 个 MenuItem 对象(不是字典!)。 # MenuItem(...) 就是在“新建一个对象”,每 new 一次就得到一份独立的属性。 # 用关键字实参传,可读性比按位置传好得多。 self.menu = [ MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5), MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5), MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3), ]
# 返回所有饮品名拼成的一串,例如 "latte/espresso/cappuccino/" # 无参数(除了 self);返回值:str def get_items(self): """Returns all the names of the available menu items""" options = "" # 遍历列表里的每个 MenuItem 对象,item 是一个对象,item.name 取它的属性。 for item in self.menu: options += f"{item.name}/" return options
# 按名字找饮品。 # 参数 order_name:用户输入的饮品名(str) # 返回值:找到就返回那个 MenuItem 对象;找不到打印提示并返回 None def find_drink(self, order_name): """Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None""" for item in self.menu: if item.name == order_name: # return 会立刻结束整个方法,循环也随之停止——比 break 再返回更直接。 return item # 循环跑完都没 return,说明没找到;函数末尾自然返回 None。 # 调用方必须处理 None,否则下一步 item.cost 会 AttributeError。 print("Sorry that item is not available.")
class CoffeeMaker: """Models the machine that makes the coffee""" # 库存是这台“机器”自己的状态,所以放在 __init__ 里成为实例属性。 # 注意:库存属于对象,不属于类——如果你 new 两台 CoffeeMaker,它们各有各的库存。 def __init__(self): self.resources = { "water": 300, "milk": 200, "coffee": 100, }
# 打印库存。self 用来访问自己的属性,不需要外部参数。 def report(self): """Prints a report of all resources.""" print(f"Water: {self.resources['water']}ml") print(f"Milk: {self.resources['milk']}ml") print(f"Coffee: {self.resources['coffee']}g")
# 判断某杯饮品能不能做。 # 参数 drink:MenuItem 对象(注意不是名字字符串) # 返回值:True 够料 / False 缺料 def is_resource_sufficient(self, drink): """Returns True when order can be made, False if ingredients are insufficient.""" can_make = True # for item in 字典:遍历拿到的是“键”,这里是 "water" / "milk" / "coffee"。 # 用同一套代码处理三种原料,就不用写三遍 if——这就是用字典存原料的好处。 for item in drink.ingredients: # 配方用量 > 现有库存 → 缺料 if drink.ingredients[item] > self.resources[item]: print(f"Sorry there is not enough {item}.") can_make = False return can_make
# 真正扣料并出咖啡。无返回值(副作用是修改库存 + 打印)。 def make_coffee(self, order): """Deducts the required ingredients from the resources.""" for item in order.ingredients: # -= 是“原地减”:等于 self.resources[item] = self.resources[item] - 用量 # 方括号赋值就是“改字典里这个键的值”,所以是原地修改。 self.resources[item] -= order.ingredients[item] print(f"Here is your {order.name} ☕️. Enjoy!")
coffee_choice = menu.find_drink(choice) if coffee_maker.is_resource_sufficient(espresso) and money_machine.make_payment(espresso.cost): coffee_maker.make_coffee(coffee_choice)
What would you like? Choose between espresso, latte or cappuccino: latte Please insert coins. How many quarters?: 10 ... Here is $0.0 in change. Here is your latte ☕️. Enjoy!
易错点
__init__ 前后各两个下划线,写成一个会变成普通方法,实例化时报错。
方法里忘写 self:def report(): 定义在类里,调用时参数个数对不上。
类属性被误改:self.COIN_VALUES["x"]=... 会改到所有实例共享的字典。
None 没有属性:查找失败后继续调用方法必崩。
动手改
修掉 espresso → coffee_choice 的 bug。
给 Menu 加 add_item(),支持运行时新增饮品。
把 menu.py 里的 cappuccino 牛奶量(50)和 Day 15 的配方(100)对齐,思考"数据不一致"是怎么产生的。
源文件逐个讲解
6 个文件,四个 .py 是四个类,这是全书第一次「一个类一个文件」。
文件
行数
职责
menu.py
35
MenuItem + Menu:菜单与单品
coffee_maker.py
30
CoffeeMaker:库存、检查、出货
money_machine.py
40
MoneyMachine:收币、找零、记账
main.py
32
组装并跑主循环
README.md
9
说明页
两个 .pdf
—
类设计文档 + 需求文档
menu.py(35 行)——两个类
1 2 3 4 5 6 7 8 9 10
class MenuItem: """Models each Menu Item.""" def __init__(self, name, water, milk, coffee, cost): self.name = name self.cost = cost self.ingredients = { "water": water, "milk": milk, "coffee": coffee }
def is_resource_sufficient(self, drink): can_make = True for item in drink.ingredients: if drink.ingredients[item] > self.resources[item]: print(f"Sorry there is not enough {item}.") can_make = False return can_make
for item in drink.ingredients 遍历字典拿到的是键(water/milk/coffee),然后用同一个键去 self.resources 里查。「两份字典键名一致」是这个循环能成立的前提——这是隐式契约,没有类型系统保证,改键名就会 KeyError。
can_make 标志位保留了 Day 15 的「一次报全所有缺料」的优点。
1 2 3 4
def make_coffee(self, order): for item in order.ingredients: self.resources[item] -= order.ingredients[item] print(f"Here is your {order.name} ☕️. Enjoy!")
while on: choice = input(f"What would you like? ...") if choice == 'off': on = False elif choice == 'report': coffee_maker.report() money_machine.report() else: coffee_choice = menu.find_drink(choice) if coffee_maker.is_resource_sufficient(espresso) and money_machine.make_payment(espresso.cost): coffee_maker.make_coffee(coffee_choice)
这一行是全天最严重的 bug:
1
coffee_maker.is_resource_sufficient(espresso) and money_machine.make_payment(espresso.cost)
coffee_choice = menu.find_drink(choice) if coffee_choice is None: continue if coffee_maker.is_resource_sufficient(coffee_choice) and money_machine.make_payment(coffee_choice.cost): coffee_maker.make_coffee(coffee_choice)
还有 None 的问题:输入 "tea",find_drink 打印「不可用」并返回 None,接着 is_resource_sufficient(espresso) 为真、付款也走了,最后 make_coffee(None) → AttributeError: 'NoneType' object has no attribute 'ingredients'。钱已经收了。
and 的短路:如果库存不够,make_payment 不会被调用,用户不会被要求投币——这个顺序是对的。
这份代码的问题
espresso 硬编码(最严重):检查、收费都用了错的饮品。
find_drink 返回 None 没被拦住,导致崩在 make_coffee,且钱已扣。
MenuItem 定义了两份,milk 一处 50 一处 100,互相矛盾。
latte、cappuccino 两个变量创建了却没用。
MoneyMachine.money_received 累加不复位(异常路径下会串账)。
Menu.find_drink 里 print:查询函数带副作用。
README.md(9 行)
标题 Day 16 - Object Oriented Programming (OOP),知识点:Constructing Objects and Accessing their Attributes and Methods、How to Add Python Packages and use PyPi、Modifying Object Attributes and Calling Methods。
「PyPi」对应 pip install——这一天开始装第三方包(本目录没有 requirements.txt,但 Day 61 之后会有)。