我知道'super'调用父类的方法。这是jekyll项目的代码:
def read_yaml(base, name)
super(base, name)
self.extracted_excerpt = extract_excerpt
end
这是一个类声明:
class Post
没有父类。在这种背景下,什么是“超级”?
答案 0 :(得分:5)
super
不仅调用父类的方法,还调用包含模块中的方法。
一般的解决方案顺序是
在这种情况下,它是Convertible#read_yaml
。
答案 1 :(得分:3)
包含模块会将其添加为类的祖先,允许使用super
调用其方法。 Post
包括Comparable
和Convertible
,因此超级方法属于其中一个类。
例如:
module Foo; end
class Bar
include Foo
end
Bar.ancestors
# [Bar, Foo, Object, Kernel, BasicObject]
答案 2 :(得分:-3)
在Ruby中, 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'
如果没有相同名称的父方法,则会引发异常。
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’
希望这会有所帮助。