0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[py2rb] 多重継承の4

Last updated at Posted at 2022-02-18

はじめに

移植やってます。
( 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

20220218.png

サーチ順として、ThSe1Se2Fiといってoriginalを出力しています。

dummy_methodでエラーになるので、大丈夫と思われ。

メモ

  • Python の 多重継承の4 を学習した
  • 百里を行く者は九十里を半ばとす
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?