Ruby 的 super 仅用于继承中,用来给子方法调用父方法。
super 例子
class Parent
def method(a, b)
puts "#{a} - #{b}"
end
end
class ChildA < Parent
def method(a, b)
super(b, a)
end
end
class ChildB < Parent
def method(a, b)
super
end
end
child_a = ChildA.new
child_b = ChildB.new
child_a.method('a', 'b')
child_b.method('a', 'b')
输出结果
b - a
a - b
super 解释
super 用于调用父类的方法,分为带参数和不带参数两种使用方法。
不带参数调用时,不要写括号,写括号就变成带参数调用了,这是需要注意的点。
假设父方法是不定参数 *args
的方式,而如果子方法通过 super()
调用父方法,此时子方法的参数并没有传给父方法,这种将会出现隐秘的 bug。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。