Menu
CoddyTech

接口字段与调用

Coddy 面向 Go 开发者的 Python 课程的第 38 课,共 48 课。

Go 结构体可以存储一个接口类型的协作者,让实现方式可以变化。Python 对象可以存储一个协作者,并调用所需的方法,而无需声明接口字段类型。账单负责协调流程,费率负责定价。每次都查找当前协作者,就能让替换影响后续调用。把它的公式复制到账单中会破坏这种分离,并拒绝不熟悉但兼容的策略。

Go

Go 代码片段:声明位于 main 上方,语句位于 main 内。导入:fmt。验证包包含完整程序。

type Pricer interface { Cost(int) int }
type Rate struct { Cents int }
func (r Rate) Cost(units int) int { return r.Cents * units }
type Bill struct { Rate Pricer }
func (b Bill) Total(units int) int { return b.Rate.Cost(units) }
// 在 main 函数中:
b := Bill{Rate: Rate{Cents: 4}}
fmt.Println(b.Total(3))
b.Rate = Rate{Cents: 7}
fmt.Println(b.Total(3))

Python

class Rate:
    def __init__(self, cents):
        self.cents = cents
    def cost(self, units):
        return self.cents * units
class Bill:
    def __init__(self, rate):
        self.rate = rate
    def total(self, units):
        return self.rate.cost(units)
b = Bill(Rate(4))
print(b.total(3))
b.rate = Rate(7)
print(b.total(3))

移植陷阱

如果契约只要求提供 cost(units),就不要要求特定的类名。Python 类型提示可以描述协议,但普通的鸭子类型调用无需共享基类也能正常工作。

challenge icon

挑战

入门

将 Rate(cents).cost(units) 实现为乘法运算,并让 UsageBill(rate).total(units) 委托给当前存储的 rate.cost(units)。驱动程序会读取费率、用量、替换费率和奖金(均为非负整数),输出第一个总额,将协作者替换为一个计算 replacement_rate * units + bonus 的对象,然后再次输出。与 Go 中由接口类型字段保存的值一样,应委托给当前协作者,而不是复制它的计算公式。

可编辑文件:rate.py、usage_bill.py。保留提供的导入语句和必需的 API 名称。锁定的 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))
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Go 开发者的 Python中的所有课

自己练习: Python 在线编译器