【发布时间】:2011-01-08 03:48:03
【问题描述】:
这段代码中的 super 是什么意思?
def initialize options = {}, &block
@filter = options.delete(:filter) || 1
super
end
据我所知,这就像递归调用函数,对吧?
【问题讨论】:
标签: ruby
这段代码中的 super 是什么意思?
def initialize options = {}, &block
@filter = options.delete(:filter) || 1
super
end
据我所知,这就像递归调用函数,对吧?
【问题讨论】:
标签: ruby
no... super 调用父类的方法,如果存在的话。此外,正如@EnabrenTane 指出的那样,它还将所有参数传递给父类方法。
【讨论】:
super()而不是super,则不会向父方法传递任何参数。
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’
【讨论】:
super 使用相同的参数调用它们。没有什么可以说如果父级接受,子级不能将参数的子集传递给父级。
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")
子类中的super(不带括号)将调用父方法与传递给原始方法的参数完全相同(因此Bar#show中的super变为super(“Hello Ruby”)并导致错误,因为父方法不带任何参数)
【讨论】:
我知道这已经晚了,但是:
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进一步学习
【讨论】:
奖金:
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"
【讨论】:
类的方法中的Super,比如test_method,用于调用另一个同名的方法,即父类的test_method。 super关键字上面和下面的代码都会正常执行,super类的方法的所有代码动作都会包含在super关键字的地方。
【讨论】: