superとか不明点
勉強会の時もLingrで聞いてみたんだけど、rubyで 親クラスのメソッドAを子クラスでオーバライドした状態で、子クラスの別のメソッドBから親クラスのメソッドAを呼び出す方法ってないんだろうか?
pythonでいうと
class Parent(object): def foo(self): print "parent foo" def bar(self): print "parent bar" class Child(Parent): def foo(self): print "child foo" def bar(self): print "child bar -- and ", super(Child, self).foo() Child().bar()
sikibu:rubystudy kuro$ python super.py child bar -- and parent foo
てなの*1。
class Parent def foo puts "parent foo" end def bar puts "parent bar" end end class Child < Parent def foo puts "child foo" end def bar print "child bar -- and " super.foo end end Child.new.bar
sikibu:rubystudy kuro$ ruby super.rb child bar -- and parent bar super.rb:16:in `bar': undefined method `foo' for nil:NilClass (NoMethodError) from super.rb:20
superが単独評価されてfooがnilで呼ばれようとして失敗。実際 reference でも「現在のメソッドがオーバーライドしている」メソッドは呼び出せる,とは書いてあるけど、その他のメソッドについて書いてない。
ンなアホ設計スンナ、というMatzふぃろそふぃなのかな。
追記:
起きたらほぼ答をコメントしてもらってた(ありがたや)。一応試してみたけど、流石にヘンテコ。
class Child < Parent def foo puts "child foo" end def bar print "child bar -- and " Parent.instance_method(:foo).bind(self).call end end
sikibu:rubystudy kuro$ ruby super.rb child bar -- and parent foo
変な使い方でExtremely carefulなんだろうけれども、それにしても面白いな。この仕組み。
さらに追記:
寝ぼけてた。:fooだ:foo。直しました。