ruby 中super和super()的区别

我们经常要在子类的initialize方法中调用super和super()。

从语法上说super和super()是有微妙区别的。

  • super不带括号表示调用父类的同名函数,并将本函数的所有参数传入父类的同名函数;

  • super()带括号则表示调用父类的同名函数,但是不传入任何参数;

演示代码如下:

 1 class SParent
 2     def initialize *args
 3         args.each {|arg| puts arg}
 4     end
 5 end
 6 
 7 class SChild < SParent
 8     def initialize a, b, c
 9         super
10     end
11 end
12 
13 a, b, c = *%W[a b c]
14 SChild.new a, b, c # puts a, b, c if super

15 SChild.new a, b, c # puts nothing if super()

 

 

可以看出当SChild的initialize中调用super()时,代码是不会打印任何信息的。这是因为super()没有向SParent的initialize方法传任何参数。
posted @ 2011-07-23 14:09  乙醇  阅读(3881)  评论(0编辑  收藏  举报

友情链接 虫师的blog  测试教程网  重定向科技  省略