我曾经super初始化父类,但我看不到从子类方法调用父类的任何方法.
我知道PHP和其他语言都有这个功能,但是在Ruby中找不到一个很好的方法.
在这种情况下会怎样做?
Mar*_*yer 85
如果方法是相同的名称,即您覆盖了一个方法,您可以简单地使用super.否则您可以使用alias_method或绑定.
class Parent
def method
end
end
class Child < Parent
alias_method :parent_method, :method
def method
super
end
def other_method
parent_method
#OR
Parent.instance_method(:method).bind(self).call
end
end
Run Code Online (Sandbox Code Playgroud)
mae*_*ics 18
该super关键字调用父类的同名方法:
class Foo
def foo
"#{self.class}#foo"
end
end
class Bar < Foo
def foo
"Super says: #{super}"
end
end
Foo.new.foo # => "Foo#foo"
Bar.new.foo # => "Super says: Bar#foo"
Run Code Online (Sandbox Code Playgroud)
Gra*_*wan 14
superRuby中的关键字实际上在父类中调用了一个同名的方法.(来源)
class Foo
def foo
# Do something
end
end
class Bar < Foo
def foo
super # Calls foo() method in parent class
end
end
Run Code Online (Sandbox Code Playgroud)
Chr*_*bek 11
其他人已经说好了.只需另外注意一点:
不支持在超类中super.foo调用方法的语法.相反,它会调用-method并在返回的结果上尝试调用.foosuperfoo
class A
def a
"A::a"
end
end
class B < A
def a
"B::a is calling #{super.a}" # -> undefined method `a` for StringClass
end
end
Run Code Online (Sandbox Code Playgroud)
从 Ruby 2.2 开始,super_method还可以用于从方法 b 调用方法 a 的 super。
method(:a).super_method.call
Run Code Online (Sandbox Code Playgroud)
class Parent
def self.parent_method
"#{self} called parent method"
end
def parent_method
"#{self} called parent method"
end
end
class Child < Parent
def parent_method
# call parent_method as
Parent.parent_method # self.parent_method gets invoked
# call parent_method as
self.class.superclass.parent_method # self.parent_method gets invoked
super # parent_method gets invoked
"#{self} called parent method" # returns "#<Child:0x00556c435773f8> called parent method"
end
end
Child.new.parent_method #This will produce following output
Parent called parent method
Parent called parent method
#<Child:0x00556c435773f8> called parent method
#=> "#<Child:0x00556c435773f8> called parent method"
Run Code Online (Sandbox Code Playgroud)
self.class.superclass == Parent #=> true
Parent.parent_method并且self.class.superclass会调用while 的
self.parent_method(类方法)调用 的(实例方法)。Parentsuperparent_methodParent
| 归档时间: |
|
| 查看次数: |
62513 次 |
| 最近记录: |