Ruby编程:继承、混合与基本类型详解
1. 继承、混合与设计
1.1 方法调用与查找链
在 Ruby 中,当调用 execute 方法时,会按照特定的查找链执行。以下是示例代码:
class Parent
def execute
puts "parenting"
end
end
module Log
def execute
puts "logging"
super
end
end
module Caller
def execute
puts "calling"
super
end
end
class Child < Parent
prepend Log
include Caller
def execute
puts "childing"
super
end
end
puts Child.new.execute
运行结果如下:
logging
childing
calling
parenting
当调用 execute 方法时,Ruby 首先会查看前置模块 Log 并执行其中的方法。该方法调用 super 后,查找链会向上继续到实际的 Child 类。接着, Child 类
超级会员免费看
订阅专栏 解锁全文
90

被折叠的 条评论
为什么被折叠?



