はじめに
移植やってます。
( from python 3.7 to ruby 2.7 )
多重継承 (Python)
前回の記事で、多重継承は表現できたものの、継承の継承は表現できていなかったので、やってみた。
delegate (Ruby)
require 'delegate'
class Fi
  def original_method(*args, **kwargs)
    'original'
  end
end
class Se1
  def method_missing(method, ...)
    'dummy'
  end
end
class Se2
  def initialize(...)
    @c = SimpleDelegator.new(Fi).new(...)
    @k =[@c]
  end
  def method_missing(method, ...)
    @k.each do |x|
      if x.respond_to?(method)
        return x.method(method).call(...)
      else
        if x.method_missing(method, ...) != 'dummy'
          return x.method_missing(method, ...)
        end
      end
    end
  end
end
class Th
  def initialize(...)
    @c1 = SimpleDelegator.new(Se1).new(...)
    @c2 = SimpleDelegator.new(Se2).new(...)
    @k =  [@c1, @c2]
  end
  def method_missing(method, ...)
    @k.each do |x|
      if x.respond_to?(method)
        return x.method(method).call(...)
      else
        if x.method_missing(method, ...) != 'dummy'
          return x.method_missing(method, ...)
        end
      end
    end
  end
end
third = Th.new
puts third.original_method
puts third.dummy_method
# output
original
`block in method_missing': private method `method_missing' called
サーチ順として、Th→Se1→Se2→Fiといってoriginalを出力しています。
dummy_methodでエラーになるので、大丈夫と思われ。
メモ
- Python の 多重継承の4 を学習した
 - 百里を行く者は九十里を半ばとす
 
