Ruby中的超级关键字

mab*_*sif 50 ruby

这段代码中的超级是什么?

def initialize options = {}, &block
  @filter = options.delete(:filter) || 1
  super
end
Run Code Online (Sandbox Code Playgroud)

据我所知,这就像递归调用函数一样,对吧?

set*_*rgo 64

no ... super调用父类的方法(如果存在).另外,正如@EnabrenTane指出的那样,它也将所有参数传递给父类方法.

  • 另外,如果你编写`super()`而不是`super`,则不会将任何参数传递给父方法:http://bit.ly/hsQtfD (44认同)
  • 默认情况下,在调用时,也会将给定的参数传递给父函数 (9认同)

von*_*rad 55

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'
Run Code Online (Sandbox Code Playgroud)

您可以调用的次数没有限制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'
Run Code Online (Sandbox Code Playgroud)

但是,如果没有相同名称的父方法,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’
Run Code Online (Sandbox Code Playgroud)

  • "super使用相同的参数调用同名的父方法." 一个*unadorned*`super`用相同的参数调用它们.没有什么可以说孩子不能将参数的子集传递给父母,如果这是父母所采取的. (6认同)

cvi*_*bha 21

超级关键字可以用来调用同名的方法进行调用的类的超类.

它将所有参数传递给父类方法.

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")
Run Code Online (Sandbox Code Playgroud)

ArgumentError:参数数量错误(1表示0)

子类中的super(没有括号)将使用与传递给原始方法的完全相同的参数调用父方法(因此Bar#show中的超级内容变为超级("Hello Ruby")并导致错误,因为父方法不接受任何参数)