T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 16 天:面向对象入门:用类重写咖啡机

这是「Python 100 天」系列第 16 天的学习笔记:面向对象入门:用类重写咖啡机。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

把 Day 15 的"一堆函数 + 全局变量"重写成三个类:MenuItem(饮品)、Menu(菜单)、CoffeeMaker(咖啡机)、MoneyMachine(收银机)。README 知识点:类与对象、构造对象、访问属性与方法、用 PyPI 装包、修改属性与调用方法。

一、类和对象是什么

类 = 图纸,对象 = 按图纸造出来的东西。

1
2
3
4
5
6
7
8
9
10
11
class Dog:
def __init__(self, name, age): # 构造方法
self.name = name # 属性
self.age = age

def bark(self): # 方法
print(f"{self.name} 汪汪")

d = Dog("旺财", 3) # 实例化,自动调用 __init__
d.bark() # 调用方法
print(d.name) # 访问属性

三个必须记住的点:

  1. __init__ 是构造方法,Dog(...) 时自动执行,用来给属性赋初值。
  2. self 是实例自身的引用,等价于 C++ 的 this,但必须显式写在参数列表第一位。调用时不用传,Python 自动填。
  3. 属性挂在 self 上,方法里访问自己的属性必须写 self.xxx,不能只写 xxx。

二、类属性 vs 实例属性

1
2
3
4
5
6
class MoneyMachine:
CURRENCY = "$" # 类属性,所有实例共享
COIN_VALUES = {"quarters": 0.25, ...}

def __init__(self):
self.profit = 0 # 实例属性,每个对象一份

类属性适合放常量/配置;实例属性放各自的状态。访问都用 self.CURRENCY,找不到实例属性时会回退到类属性。

三、装第三方包

1
pip install requests

PyPI 是 Python 的包仓库。装完 import requests 就能用。注意虚拟环境:真实项目应在 python3 -m venv .venv 里装,避免污染系统 Python(Day 35 会用到环境变量,也是同一套工程习惯)。

代码全文

主程序只负责"组装零件 + 主循环":

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# ============================================================
# day16/main.py —— 咖啡机主程序(面向对象版本)
# 作用:把 menu / coffee_maker / money_machine 三个类“组装”起来跑起来。
# 知识点:跨文件 import、实例化对象、方法调用、对象之间传参
# ============================================================

# 从同目录的模块里导入类。python 找模块时先看“当前脚本所在目录”,
# 所以 menu.py / coffee_maker.py / money_machine.py 必须和本文件放一起。
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine

# List of drinks
# 这里又手工造了三个 MenuItem 对象。它们和 Menu.__init__ 里那三个是“两套独立的数据”,
# 而且 cappuccino 的 milk 这里写 100、menu.py 里写 50——同一份数据写两处,早晚不一致。
# 这也是后面要引入“单一数据源”的原因:同一件事只该有一处定义。
espresso = MenuItem("espresso", 50, 0, 18, 1.5)
latte = MenuItem("latte", 200, 150, 24, 2.5)
cappuccino = MenuItem("cappuccino", 250, 100, 24, 3.0)

# For ordering drinks and checking if drink is available
# 类名后面加括号 = 创建一个实例(对象),并自动执行 __init__。
menu = Menu()

# Printing report of all resources, checking if resources are sufficient, making coffee
coffee_maker = CoffeeMaker()

# Printing report and taking payment
money_machine = MoneyMachine()

on = True
while on:
choice = input(f"What would you like? Choose between espresso, latte or cappuccino: ")
if choice == 'off':
print("Have a good one!")
on = False
elif choice == 'report':
# 两个对象各自打印自己的报表:库存归咖啡机管,钱归收银机管。
coffee_maker.report()
money_machine.report()
else:
# find_drink 找不到时返回 None(并打印提示),所以这里要小心 None。
coffee_choice = menu.find_drink(choice)
# 这行有个真 bug:查库存和收款传的都是 espresso,而不是用户选的 coffee_choice。
# 结果是不管点什么都按 espresso 的料和价处理(做出来的却是 coffee_choice)。
# 正确写法:coffee_maker.is_resource_sufficient(coffee_choice) 和
# money_machine.make_payment(coffee_choice.cost)
# 另外 and 是“短路求值”:左边 False 就不会去收钱,这一点用得对。
if coffee_maker.is_resource_sufficient(espresso) and money_machine.make_payment(espresso.cost):
# coffee_choice 可能是 None;这里没判断,
# 输错饮品名会 AttributeError: 'NoneType' object has no attribute 'name'。
coffee_maker.make_coffee(coffee_choice)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# ============================================================
# day16/menu.py —— 菜单与饮品(面向对象版)
# 作用:定义“一种饮品”和“整份菜单”两个类。
# 知识点:class、__init__ 构造函数、self、实例属性、列表存对象、
# 方法返回值(找到返回对象,找不到返回 None)
# ============================================================


# 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.")

coffee_maker.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# ============================================================
# day16/coffee_maker.py —— 咖啡机本体(负责库存与制作)
# 作用:一个类装下“库存、查库存、扣库存、出咖啡”四件事。
# 知识点:类把“数据 + 操作”打包、self.resources、方法间互相调用、for 遍历字典
# ============================================================


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!")

money_machine.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# ============================================================
# day16/money_machine.py —— 收银模块(收硬币、算找零、记账)
# 作用:处理“投币 → 判断钱够不够 → 找零 → 记入利润”的全过程。
# 知识点:类属性 vs 实例属性、字典存面值、round()、返回值当“成功/失败”信号
# ============================================================


class MoneyMachine:

# 全大写是“常量”的命名惯例(Python 不会真的阻止你修改)。
# 这里 CURRENCY 和 COIN_VALUES 写在 class 里、且在 __init__ 之外,
# 它们是“类属性”:所有对象共享一份,用 self.CURRENCY 也能读到。
CURRENCY = "$"

# 硬币面值表:键是硬币名,值是美元面值。
# 有了这张表,收币时就能用“遍历 + 相乘累加”代替四个 if。
COIN_VALUES = {
"quarters": 0.25,
"dimes": 0.10,
"nickles": 0.05,
"pennies": 0.01
}

# 实例属性:profit(累计利润)和 money_received(本次投入,结算后清零)。
# 这两个是“每台机器各自的账本”,所以必须放在 __init__ 里。
def __init__(self):
self.profit = 0
self.money_received = 0

# 打印当前利润。无参数、无返回值。
def report(self):
"""Prints the current profit"""
print(f"Money: {self.CURRENCY}{self.profit}")

# 逐种硬币问数量并累加金额。
# 无参数(硬币种类来自类属性 COIN_VALUES);返回值:本次投入总额(float)
def process_coins(self):
"""Returns the total calculated from coins inserted."""
print("Please insert coins.")
for coin in self.COIN_VALUES:
# int(input(...)):把“枚数”转成整数;
# * self.COIN_VALUES[coin]:枚数 × 面值 = 这种硬币的金额;
# += 累加到 self.money_received。
# 注意这里没有把 money_received 清零,它是“本次投币”的累加器,
# 由 make_payment 在结算后负责归零。
self.money_received += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin]
return self.money_received

# 收钱并判断是否够付。
# 参数 cost:这杯咖啡的价格(float)
# 返回值:True 付款成功;False 钱不够(已退款)
def make_payment(self, cost):
"""Returns True when payment is accepted, or False if insufficient."""
# 先收币(内部会累加金额),返回值这里没接,因为下面直接读 self.money_received。
self.process_coins()
if self.money_received >= cost:
# round(x, 2):四舍五入到 2 位小数,避免 0.30000000000000004 这种浮点误差。
change = round(self.money_received - cost, 2)
print(f"Here is {self.CURRENCY}{change} in change.")
# 利润只加售价,不加投入总额(多收的部分要退回去)。
self.profit += cost
# 结算完清零,为下一位顾客准备。
self.money_received = 0
return True
else:
print("Sorry that's not enough money. Money refunded.")
# 钱不够也要清零,否则下一次投币会带着上次的余额,越算越乱。
self.money_received = 0
return False

代码走读

  1. MenuItem.__init__(self, name, water, milk, coffee, cost):一个饮品对象自带名称、三种原料用量、价格。Menu 初始化时造三个 MenuItem 放进列表——对象里装对象。
  2. Menu.find_drink(order_name):遍历列表按名字找,找到返回对象,找不到打印提示并返回 None。
  3. CoffeeMaker.is_resource_sufficient(drink):for item in drink.ingredients 遍历配方里的每种原料,逐一和 self.resources 比较。这里体现了 OOP 的好处:咖啡机不需要知道"latte 是什么",只要 drink 能给出 ingredients 就行。
  4. CoffeeMaker.make_coffee(order):按配方扣库存,打印出货。
  5. MoneyMachine.process_coins():遍历 COIN_VALUES 的键询问数量,累加到 self.money_received。
  6. MoneyMachine.make_payment(cost):钱够就找零、加利润、清零;不够就退款返回 False。
  7. 主循环:off 退出、report 打两份报表、其它情况查找饮品 → 检查原料 → 收款 → 制作。

这份代码有一个关键 bug

主循环里:

1
2
3
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)

检查原料和收钱用的都是 espresso(写死的浓缩),而不是用户选的 coffee_choice。结果:点任何饮品都按浓缩的 50ml 水、18g 咖啡、1.5 美元结算,但最后做出来的却是你点的那杯。

正确写法:

1
2
if coffee_maker.is_resource_sufficient(coffee_choice) and money_machine.make_payment(coffee_choice.cost):
coffee_maker.make_coffee(coffee_choice)

这就是"变量名相似导致看漏"的典型。另外 find_drink 找不到时返回 None,下一行 is_resource_sufficient(None) 会 AttributeError,也要先判空。

运行示例

1
2
3
4
5
6
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!

易错点

  1. __init__ 前后各两个下划线,写成一个会变成普通方法,实例化时报错。
  2. 方法里忘写 self:def report(): 定义在类里,调用时参数个数对不上。
  3. 类属性被误改:self.COIN_VALUES["x"]=... 会改到所有实例共享的字典。
  4. None 没有属性:查找失败后继续调用方法必崩。

动手改

  • 修掉 espresso → coffee_choice 的 bug。
  • 给 Menu 加 add_item(),支持运行时新增饮品。
  • 把 menu.py 里的 cappuccino 牛奶量(50)和 Day 15 的配方(100)对齐,思考"数据不一致"是怎么产生的。

源文件逐个讲解

6 个文件,四个 .py 是四个类,这是全书第一次「一个类一个文件」。

文件 行数 职责
menu.py35MenuItem + Menu:菜单与单品
coffee_maker.py30CoffeeMaker:库存、检查、出货
money_machine.py40MoneyMachine:收币、找零、记账
main.py32组装并跑主循环
README.md9说明页
两个 .pdf—类设计文档 + 需求文档
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
}

MenuItem 是「值对象」:只装数据,没有行为(除了 __init__)。ingredients 在构造时用参数拼成字典,这样外部访问统一是 item.ingredients['water']。

注意 milk 没有默认值,所以 espresso 必须显式传 milk=0——这就比 Day 15 的「缺键 + 特判」干净多了。用 0 代替「没有」,是消除分支的常用手法。

1
2
3
4
5
6
7
class Menu:
def __init__(self):
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),
]

Menu 组合了三个 MenuItem——这是「组合优于继承」的最早示例:菜单不是一种饮品,而是包含饮品。

顺序是 latte、espresso、cappuccino,和 Day 15 的字典顺序不同(字典是 espresso、latte、cappuccino)。get_items() 会按这个顺序输出,所以屏幕上第一项是 latte。

1
2
3
4
5
    def find_drink(self, order_name):
for item in self.menu:
if item.name == order_name:
return item
print("Sorry that item is not available.")

找不到时 return 都没有——隐式返回 None,而 print 混在「查询函数」里。查询函数不该有副作用,应该只返回 None,让调用方决定打印什么。

coffee_maker.py(30 行)

1
2
3
4
class CoffeeMaker:
"""Models the machine that makes the coffee"""
def __init__(self):
self.resources = {"water": 300, "milk": 200, "coffee": 100}

库存是实例属性 self.resources,不再是模块级全局字典。多个 CoffeeMaker() 各有各的库存——这就是类相对全局变量的最大好处:状态被封装在对象里。

1
2
3
4
5
6
7
    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!")

扣料也是按同一套键循环,三行搞定,不需要像 Day 15 那样为 milk 特判。

money_machine.py(40 行)

1
2
3
class MoneyMachine:
CURRENCY = "$"
COIN_VALUES = {"quarters": 0.25, "dimes": 0.10, "nickles": 0.05, "pennies": 0.01}

CURRENCY 和 COIN_VALUES 写在类里、没有 self.——这是类属性,所有实例共享同一份。它们是不会变的数据,放类属性比放实例属性省内存,也表明「这是常量」。

1
2
3
4
5
6
    def __init__(self):
self.profit = 0
self.money_received = 0

def report(self):
print(f"Money: {self.CURRENCY}{self.profit}")

profit(累计收入)和 money_received(本次投币)是实例属性,每台机器独立。

1
2
3
4
5
    def process_coins(self):
print("Please insert coins.")
for coin in self.COIN_VALUES:
self.money_received += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin]
return self.money_received

遍历 COIN_VALUES 自动问四种币,加一种硬币只改类属性。这是「数据驱动」的写法,比 Day 15 写死四个 input 强。

但 self.money_received += 是累加而不是清零后重算:正常流程里 make_payment 成功/失败都会把它置 0,所以能跑;万一中间抛异常,下一次投币会把上次的钱算进去。

1
2
3
4
5
6
7
8
9
10
11
12
    def make_payment(self, cost):
self.process_coins()
if self.money_received >= cost:
change = round(self.money_received - cost, 2)
print(f"Here is {self.CURRENCY}{change} in change.")
self.profit += cost
self.money_received = 0
return True
else:
print("Sorry that's not enough money. Money refunded.")
self.money_received = 0
return False

返回布尔值,让调用方决定要不要出货——这是「把判断和动作分开」的设计。self.profit += cost(不是 += money_received),因为多收的部分要找零退掉。

main.py(32 行)——组装层

1
2
3
4
5
6
7
8
9
10
11
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine

espresso = MenuItem("espresso", 50, 0, 18, 1.5)
latte = MenuItem("latte", 200, 150, 24, 2.5)
cappuccino = MenuItem("cappuccino", 250, 100, 24, 3.0)

menu = Menu()
coffee_maker = CoffeeMaker()
money_machine = MoneyMachine()

这里创建了 3 个 MenuItem,但 Menu() 内部又自己创建了一套——同样的饮品定义了两遍,而且 menu.py 里 cappuccino 的 milk 是 50,这里写的是 100。两处数据不一致,就是 bug 的温床。espresso/latte/cappuccino 这三个变量后面只用了 espresso(见下),另外两个纯属多余。

1
2
3
4
5
6
7
8
9
10
11
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)

检查的是 espresso,收的也是 espresso.cost,和用户选的 coffee_choice 完全无关。结果:

  • 点 latte(2.5 美元),只收 1.5 美元;
  • 点 cappuccino(需要 250ml 水),只要 espresso 的 50ml 水够就放行,出货时才发现水不够(make_coffee 直接减成负数)。

正确写法:coffee_choice 一拿到就用它:

1
2
3
4
5
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 不会被调用,用户不会被要求投币——这个顺序是对的。

这份代码的问题

  1. espresso 硬编码(最严重):检查、收费都用了错的饮品。
  2. find_drink 返回 None 没被拦住,导致崩在 make_coffee,且钱已扣。
  3. MenuItem 定义了两份,milk 一处 50 一处 100,互相矛盾。
  4. latte、cappuccino 两个变量创建了却没用。
  5. MoneyMachine.money_received 累加不复位(异常路径下会串账)。
  6. 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 之后会有)。

四个 .py 的依赖关系

1
2
3
4
5
6
main.py
├── menu.Menu, menu.MenuItem
├── coffee_maker.CoffeeMaker
└── money_machine.MoneyMachine
↑
coffee_maker 不认识 Menu,只认「有 .ingredients 的东西」

CoffeeMaker 只依赖「传进来的对象有 .ingredients 和 .name」,不 import menu。这叫鸭子类型:不看类型,只看行为。所以 coffee_maker.py 里一行 from menu import ... 都没有。

微信收款码 微信
支付宝收款码 支付宝
评论