此代码中的超级是什么?
def initialize options = {}, &block
@filter = options.delete(:filter) || 1
super
end
据我所知,这就像递归调用函数一样,对吗?
答案 0 :(得分:61)
no ... super调用父类的方法(如果存在)。另外,正如@EnabrenTane指出的那样,它也将所有参数传递给父类方法。
答案 1 :(得分:54)
super
使用相同的参数调用同名的父方法。对继承的类使用非常有用。
以下是一个例子:
class Foo
def baz(str)
p 'parent with ' + str
end
end
class Bar < Foo
def baz(str)
super
p 'child with ' + str
end
end
Bar.new.baz('test') # => 'parent with test' \ 'child with test'
您可以调用super
的次数没有限制,因此可以将它与多个继承的类一起使用,如下所示:
class Foo
def gazonk(str)
p 'parent with ' + str
end
end
class Bar < Foo
def gazonk(str)
super
p 'child with ' + str
end
end
class Baz < Bar
def gazonk(str)
super
p 'grandchild with ' + str
end
end
Baz.new.gazonk('test') # => 'parent with test' \ 'child with test' \ 'grandchild with test'
但是,如果没有相同名称的父方法,Ruby会引发异常:
class Foo; end
class Bar < Foo
def baz(str)
super
p 'child with ' + str
end
end
Bar.new.baz('test') # => NoMethodError: super: no superclass method ‘baz’
答案 2 :(得分:20)
super 关键字可用于调用进行调用的类的超类中的同名方法。
它将所有参数传递给父类方法。
super与super()
不同class Foo
def show
puts "Foo#show"
end
end
class Bar < Foo
def show(text)
super
puts text
end
end
Bar.new.show("Hello Ruby")
答案 3 :(得分:0)
加成:
module Bar
def self.included base
base.extend ClassMethods
end
module ClassMethods
def bar
"bar in Bar"
end
end
end
class Foo
include Bar
class << self
def bar
super
end
end
end
puts Foo.bar # => "bar in Bar"
答案 4 :(得分:0)
类的方法中的super,例如test_method,用于调用另一个具有相同名称的方法,即父类的test_method。 将在super关键字的上方和下方编写的代码将正常执行,并将在super关键字的位置包含super类方法的全部代码动作。
答案 5 :(得分:0)
我知道这很晚了,但是:
super
方法调用父类方法。
例如:
class A
def a
# do stuff for A
end
end
class B < A
def a
# do some stuff specific to B
super
# or use super() if you don't want super to pass on any args that method a might have had
# super/super() can also be called first
# it should be noted that some design patterns call for avoiding this construct
# as it creates a tight coupling between the classes. If you control both
# classes, it's not as big a deal, but if the superclass is outside your control
# it could change, w/o you knowing. This is pretty much composition vs inheritance
end
end
如果还不够,您可以从here继续学习