LoginSignup
1
0

More than 1 year has passed since last update.

[py2rb] 多重継承の5

Last updated at Posted at 2022-02-24

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

多重継承 (Python)

前回の記事の コメント にて、@Nabetani さんよりメソッドのまとめ方を教えていただきましたので、それを踏まえて再びやってみました。

20220224a.png

  • 一番目の行は、ファイル名(Rubyですとmodule名)
  • C:class, SC:継承するsuperclass
  • D:メソッド定義, DS:メソッド内でsuperを使用しているメソッド定義

継承テスト(Python)

class C5:
    s1 = None
    s3 = None
    s5 = 's5'
    def __init__(self):
        print('C5')

class C4(C5):
    s4 = 's4'
    def __init__(self):
        print('C4')
        
class C2(C4):
    s2 = 's2'
    def __init__(self):
        print('C2')
        super().__init__()

class C3:
    s3 = 's3'
    def __init__(self):
        print('C3')

class C1(C2, C3):
    s1 = 's1'
    def __init__(self):
        print('C1')
        super().__init__()
        print(self.s1)
        print(self.s2)
        print(self.s3)
        print(self.s4)
        print(self.s5)

C1()

# output
C1
C2  
C4  
s1  
s2  
None
s4  
s5 

ふむふむ。
クラス変数も受け継がれてますね。

継承テスト(Ruby)

module C5
  @@s1 = 'None'
  @@s3 = 'None'
  @@s5 = 's5'
  def __init__
    puts 'C5'
  end
end

module C4
  include C5
  @@s4 = 's4'
  def __init__
    puts 'C4'
  end
end
      
module C2
  include C4
  @@s2 = 's2'
  def __init__
    puts 'C2'
    super
  end
end

module C3
  @@s3 = 's3'
  def __init__
    puts 'C3'
  end
end

class C1
  include C2, C3
  @@s1 = 's1'

  def initialize
    __init__
  end

  def __init__
    puts 'C1'
    super
    puts @@s1
    puts @@s2
    puts @@s3
    puts @@s4
    puts @@s5
  end
end

c = C1.new
p C1.ancestors

# output
C1
C2
C4
s1
s2
s3
s4
s5
[C1, C2, C4, C5, C3, Object, Kernel, BasicObject]

s3が惜しかったですが、継承チェーンは正しいようです。

メモ

  • Python の 多重継承の5 を学習した
  • 百里を行く者は九十里を半ばとす
1
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
1
0