LoginSignup
0
0

More than 1 year has passed since last update.

はじめに

移植やってます。

多重継承 (Python)

[py2rb] 多重継承 - Qiita 再び
20211214a.png

class A(object):
    def myprint(self):
        print('A')

class B(A):
    def myprint(self):
        print('B')
        super().myprint()

class C(B):
    def myprint(self):
        print('C')
        super().myprint()

class D(A):
    def myprint(self):
        print('D')
        super().myprint()

class E(D, C):
    def myprint(self):
        print('E')
        super().myprint()

o = E()
o.myprint()

# E
# D
# C
# B
# A

class Eが画像のオレンジ色クラスです。
左側からDFSで継承されています。
class Aが上手いこと後ろに回っていますね。

どうする? (Ruby)

class A
  def myprint
    puts 'A'
  end
end

class B < A
  def myprint
    puts 'B'
    super
  end
end

class C < B
  def myprint
    puts 'C'
    super
  end
end

class D < C
  def myprint
    puts 'D'
    super
  end
end

class E < D
  def myprint
    puts 'E'
    super
  end
end

p E.ancestors

# [E, D, C, B, A, Object, Kernel, BasicObject]

一つは、継承チェーンを考えて直列に並べる。

module A
  def myprint
    puts 'A'
  end
end

class B
  include A
  def myprint
    puts 'B'
    super
  end
end

class C < B
  def myprint
    puts 'C'
    super
  end
end

module D
  include A
  def myprint
    puts 'D'
    super
  end
end

class E < C
  include D
  def myprint
    puts 'E'
    super
  end
end

p E.ancestors

[E, D, C, B, A, Object, Kernel, BasicObject]

ここでは見えませんが、ADがモジュール化できそうなのでMixinする方法

メモ

  • Python の 多重継承 を学習した
  • 道のりは遠そう
0
0
0

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