注入的协作者
Coddy 面向 Kotlin 开发者的 Python 课程的第 38 课,共 48 课。
Kotlin 的构造函数注入会存储一个协作者,Python 也可以通过实例属性实现相同的做法。两种语言都会共享传入的对象,而不是在赋值时克隆它。账单可以将定价委托给费率对象,从而将定价策略与记录处理分开。Python 不要求为该调用声明接口,但该对象必须在运行时支持相应操作。
Kotlin
class Rate { fun cost(n: Int) = 7 * n }
class Bill(private val rate: Rate) { fun total(n: Int) = rate.cost(n) }
fun main() { println(Bill(Rate()).total(2)) }Python
class Rate:
def cost(self, n):
return 7 * n
class Bill:
def __init__(self, rate):
self.rate = rate
def total(self, n):
return self.rate.cost(n)
print(Bill(Rate()).total(2))移植时的陷阱
传入可变的协作者后,它之后的更改也会被各个持有者共享。如果需要独立的快照,请明确选择复制对象。
在可编辑的模块中完成任务。锁定的 driver.py 负责执行;请保留必需的 API 名称。
挑战
入门实现 Rate(cents),其中 cost(units) 返回 cents 乘以 units;再实现 UsageBill(rate),将协作对象保存为 rate。它的 total(units) 必须委托协作对象的 cost(units)。输入为分行提供的 4 个非负整数:费率、用量、替换费率和奖励值。锁定的驱动程序会输出第一个总额,将协作对象替换为一个现成对象,该对象的 cost 为 replacement_rate * units + bonus,然后输出新的总额。账单必须使用当前的协作对象,不能缓存公式或初始结果。
锁定的驱动程序负责处理输入和输出。只提交所需的类和函数定义,并使用准确的 API 名称。不要在你的类中读取输入或打印内容。
将代码写入可编辑文件 rate.py 和 usage_bill.py。driver.py 中包含提供的输入/输出代码和 API 检查,不能编辑。保留提供的导入语句;不要在可编辑模块中读取输入或打印内容。
亲手试试
from rate import Rate
from usage_bill import UsageBill
class BonusRate:
def __init__(self, cents, bonus):
self.cents = cents
self.bonus = bonus
def cost(self, units):
return self.cents * units + self.bonus
cents, units, replacement, bonus = [int(input()) for _ in range(4)]
bill = UsageBill(Rate(cents))
print(bill.total(units))
bill.rate = BonusRate(replacement, bonus)
print(bill.total(units))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 Python中的所有课
自己练习: Python 在线编译器