继承与重写
Coddy 面向 Python 开发者的 Ruby 课程的第 32 课,共 48 课。
Ruby 类只有一个直接父类,而 Python 允许多个基类。子类会继承行为,并且可以重写同名方法。Ruby 模块提供了另一种共享行为的机制,无需再添加一个类作为父类。方法查找会决定调用哪个实现,而继承的方法可以动态调用重写后的方法。这个示例修改了声音,但没有实现数值定价任务。
Python:完整程序
class Bird:
def sound(self):
return "chirp"
class Owl(Bird):
def sound(self):
return "hoot"
print(Bird().sound())
print(Owl().sound())Ruby:完整程序
class Bird
def sound; "chirp"; end
end
class Owl < Bird
def sound; "hoot"; end
end
puts Bird.new.sound
puts Owl.new.sound挑战
简单定义 Fee#cost(units),使其返回 units*2。DiscountFee 继承 Fee 并重写 cost,使其返回 units(所有单位数均为非负数)。solve 读取 base 或 discount,后面跟着单位数,并创建所选类型的对象。
让 solve(input) 返回文本,不要打印。锁定的驱动程序会用一个末尾换行符打印返回的文本,并独立检查所需的公共 API。
你的代码放在 exercise.rb、fee.rb 和 discount_fee.rb 中。main.rb 中包含提供的输入/输出代码,不能编辑。
亲手试试
require_relative 'exercise'
require_relative 'fee'
require_relative 'discount_fee'
def check(value)
raise 'Public API check failed' unless value
end
check(DiscountFee.new.is_a?(Fee))
check(Fee.new.cost(7) == 14 && DiscountFee.new.cost(7) == 7)
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器