嵌入不等于继承
Coddy 面向 Go 开发者的 Python 课程的第 39 课,共 48 课。
Go 通过嵌入字段来提升选择器,但它没有类继承,也不会让外层结构体可赋值给嵌入类型。Python 会在括号中指定基类,并支持继承方法和重写。如果子类定义了 __init__,需要时必须调用基类的初始化。super() 遵循 Python 方法解析顺序,这比显式调用某个指定父类的方法更通用。只需要协作时,组合仍然很有用。
Go
Go 代码片段:在 main 上方声明,在 main 内编写语句。导入:fmt。验证包中包含完整程序。
type Pass struct { Price int }
func (p Pass) Cost() int { return p.Price }
type DiscountPass struct { Pass; Discount int }
func (d DiscountPass) Cost() int { n := d.Pass.Cost()-d.Discount; if n < 0 { return 0 }; return n }
// 在 main 函数中:
d := DiscountPass{Pass: Pass{Price: 100}, Discount: 15}
fmt.Println(d.Cost())
d.Price = 120
fmt.Println(d.Cost())Python
class Pass:
def __init__(self, price):
self.price = price
def cost(self):
return self.price
class DiscountPass(Pass):
def __init__(self, price, discount):
super().__init__(price)
self.discount = discount
def cost(self):
return max(0, super().cost() - self.discount)
d = DiscountPass(100, 15)
print(d.cost())
d.price = 120
print(d.cost())移植陷阱
Go 中嵌入的方法会使用其声明时指定的接收者;它们不会像 Python 方法那样通过外层值进行动态分派。不要把 Go 中提升的方法和 Python 中的方法重写视为可以互换的模型。
挑战
入门实现 Pass(label,price),保存属性,并让 cost() 返回当前价格。将 DiscountPass(label,price,discount) 实现为子类,通过 super().__init__ 初始化基类,并在重写的方法中返回 max(0, 基础价格减去折扣)。输入为标签,以及非负的价格和折扣。驱动程序会打印普通和折扣通行证的标签与价格对,然后将折扣通行证的价格增加 10,接着打印新价格;它还会检查子类关系。Go 的嵌入并不等同于继承;这个 Python 子类必须显式调用基类初始化方法。
可编辑文件:pass_model.py、discount_pass.py。保留提供的导入语句和必需的 API 名称。锁定的 driver.py 负责执行和检查,不要编辑它。
在可编辑模块中实现指定的定义,不要进行输入或打印。驱动程序负责输入和输出,也可能会用新数据再次调用这些 API,且不会产生额外输出。
亲手试试
from pass_model import Pass
from discount_pass import DiscountPass
assert issubclass(DiscountPass, Pass), "Required subclass relationship missing"
label = input()
price, discount = int(input()), int(input())
a, b = Pass(label, price), DiscountPass(label, price, discount)
print(a.label, a.cost())
print(b.label, b.cost())
b.price += 10
print(b.cost())
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 Python中的所有课
自己练习: Python 在线编译器