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.
精彩评论