开发者

calling a super class' method with a twist

Suppose I have t开发者_如何学Pythonwo classes like so:

class Parent
  def say
   "I am a parent"
  end
end

class Child < Parent
  def say
   "I am a child"
  end

  def super_say
   #I want to call Parent.new#say method here
  end
end

What are the options to do that? I thought of:

def super_say
  self.superclass.new.say #obviously the most straight forward way, but inefficient
end

def super_say
 m = self.superclass.instance_method(:say)
 m = m.bind(self)
 m.call
 #this works, but it's quite verbose, is it even idiomatic? 
end

I am looking for a way which doesn't involve aliasing Parent.new#say to something else, which would make it unique in the method lookup chain (Or is that actually the preferred way?). Any suggestions?


I tend to prefer using an alias. (I'm not quite sure I understand your objection to it.)

Example:

class Child < Parent
  alias :super_say :say

  def say
    "I am a child"
  end
end

Gives:

irb(main):020:0> c = Child.new
=> #<Child:0x45be40c>
irb(main):021:0> c.super_say
=> "I am a parent"


Your second solution (the bind()) is the one i would go for. It is verbose because what you are doing is highly unusual, but if you really need to do it -- that solution seems fine to me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜