我如何调用超类方法 [英] How do I call a super class method

查看:35
本文介绍了我如何调用超类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类 AB.B 类覆盖了 A 类的 foo 方法.类 B 有一个 bar 方法,我想在其中调用超类的 foo 方法.这种调用的语法是什么?

I have two classes A, and B. Class B overrides the foo method of class A. Class B has a bar method where I want to call the foo method of the super class. What is the syntax for such a call?

class A    
 def foo
   "hello"
 end    
end


class B < A
 def foo
  super + " world"
 end

 def bar
   # how to call the `foo` method of the super class?
   # something similar to
   super.foo
 end
end

对于类方法,我可以通过显式添加类名前缀来调用继承链上的方法.我想知道实例方法是否有类似的习惯用法.

For class methods I can call the methods up the inheritance chain by explicitly prefixing the class name. I wonder if there is a similar idiom for instance methods.

class P
 def self.x
   "x"
 end
end

class Q < P
 def self.x
   super + " x"
 end

 def self.y
   P.x
 end
end

编辑我的用例是通用的.对于特定情况,我知道我可以使用 alias 技术.这是 Java 或 C++ 中的常见功能,所以我很想知道是否可以在不添加额外代码的情况下执行此操作.

Edit My use case is general. For a specific case I know I can use alias technique. This is a common feature in Java or C++, so I am curious to know if it is possible to do this without adding extra code.

推荐答案

在 Ruby 2.2 中,您现在可以使用 Method#super_method

In Ruby 2.2, you can use Method#super_method now

例如:

class B < A
  def foo
    super + " world"
  end

  def bar
    method(:foo).super_method.call
  end
end

参考:https://bugs.ruby-lang.org/issues/9781#change-48164https://www.ruby-forum.com/topic/5356938

这篇关于我如何调用超类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆