本文介绍了调用 super() 是否会导致使用父类中的其他方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 super 的问题,我想确认一下.考虑以下代码示例:

I have a question about super that I wanted confirmed. Consider the following code example:

class InFasionHello
  def hello person
    greet person.name
  end

  def greet name
   p 'Dude, hey ' + name
  end 
end

class OldFasionedHello < InFasionHello
  def hello person
    greet person.name if person.old_fashioned
    super(person) if !person.old_fashioned
  end

  def greet name
   p 'Good Day to you ' + name + '!'
  end
end

我的问题是,如果我使用 OldFasionedHelloinfasionHello 会使用本地的 greet 给它自己还是来自该类的那个通过 super 调用它?

My question is, if I was using OldFasionedHello, would infasionHello use the local greet to it self or the one from the class that called it via super?

推荐答案

布丁的证明在于吃.

class Parent
  def foo; p self; bar; end        # This calls bar on the current object
  def bar; puts "parent bar"; end
end

class Child < Parent
  def foo; super; end              # Removing this line changes nothing
  def bar; puts "child bar"; end
end

Child.new.foo
#=> #<Child:0x007f980b051f40>
#=> child bar                      # NOTE! Not "parent bar"

调用 super 不会改变 self,如上所示.因此,您在 self 上调用的方法(通过不提供接收器显式或隐式地)仍然作用于原始实例,并将其用于 方法查找.

Calling super doesn't change the self, as seen above. As such, methods you call on self (explicitly or implicitly, by not providing a receiver) still act upon the original instance, and use it for method lookup.

调用 super() 相当于调用:

self.class.superclass.instance_method(__method__).bind(self).call

...这有助于说明您正在调用方法的实现,就好像它在当前实例上一样.另请注意,supersuper() 不同,因为前者会神奇地传递提供给当前方法的任何参数.

…which helps to illustrate that you are calling the implementation of the method as though it is on the current instance. Note also that super is not the same as super(), since the former will magically pass along whatever parameters were supplied to the current method.

这篇关于调用 super() 是否会导致使用父类中的其他方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:39