Menu
CoddyTech

显式 super 参数

Coddy 面向 Ruby 开发者的 Python 课程的第 39 课,共 48 课。

Ruby 使用小于号声明子类,Python 则在括号中列出基类。两者都可以重写继承的方法。在 Ruby 中,不带括号的 super 会转发当前方法的参数,而 Ruby 中的 super() 不会提供任何参数。Python 的 super() 会构造一个查找代理;你需要显式调用目标方法并提供它的参数。Python 的 super 会按照方法解析顺序查找,这对协作式多重继承很重要,而不是总是指定某个直接父类。对于单基类练习,调用 super().__init__ 并传入所需的基类状态,然后初始化新属性。继承一个方法不会自动扩展被重写方法的函数体。

Ruby

class Base
  def label(text)
    text + '!'
  end
end
class Child < Base
  def label(text)
    super + '?'
  end
end
puts Child.new.label('go')

Python

class Base:
    def label(self, text):
        return text + '!'
class Child(Base):
    def label(self, text):
        return super().label(text) + '?'
print(Child().label('go'))

移植陷阱

不要把 Ruby 中不带括号的 super 直接移植为 Python 中单独的 super()。必须使用 Python 的代理来调用诸如 super().cost() 这样的方法。

challenge icon

挑战

入门

实现 Pass(label, price),保存属性,并让 cost() 返回整数价格。实现子类 DiscountPass(label, price, discount),通过 super().__init__ 初始化基类状态,并保存 discount。重写 cost(),使其返回基准费用减去折扣后的金额,最低为 0。输入依次为标签、非负价格和非负折扣,每项各占一行。驱动程序会打印普通通行证和折扣通行证的标签与费用,然后将折扣通行证的 price 增加 10,并打印它的新费用。请根据当前状态计算。

锁定的驱动程序会处理输入和输出。只提交所需的类和函数定义,并使用准确的 API 名称。不要在类中读取输入或打印内容。

锁定的驱动程序还会在运行时验证所需的子类关系。

请将代码写入可编辑文件 pass_model.py 和 discount_pass.py。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())
quiz icon自我测试

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

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

自己练习: Python 在线编译器