1
0

More than 1 year has passed since last update.

[py2rb] type クラスの動的定義

Last updated at Posted at 2022-01-28

はじめに

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

type (Python)

    @classmethod
    def _make_chain(cls, sequence_maker):
        if isinstance(sequence_maker, type):
            tp = type('%sChain' % sequence_maker.__class__.__name__, (cls,), {
                'sequence_maker': sequence_maker
            })
        else:
            tp = type('FunctionChain', (cls,), {
                'sequence_maker': staticmethod(sequence_maker)
            })
        return tp

独習Python 516p

ここでのtypeはメソッドの雛型を利用して、クラスを動的に定義しています。

Class.new (Ruby)

class MC
  def self._make_chain(sequence_maker)
    if sequence_maker.instance_of?(Class)
      tp = sequence_maker.class.to_s.concat('Chain')
      tp = Class.new(self) {
        def sequence_maker
          puts 'Instance Method'
        end
        define_method(sequence_maker.to_s, instance_method(:sequence_maker))
      }
    else
      functionChain = Class.new(self)
      functionChain.define_singleton_method(sequence_maker) do
        puts 'Class Method'
      end
      return functionChain
    end
  end
end

MC._make_chain(String).new.String
MC._make_chain('aa').aa

# output
Instance Method
Class Method

Class.new(superclass)でクラスを生成。
インスタンスメソッドは、define_methodで名前を変更。
クラスメソッドは、define_singleton_methodで生成。

やっていることはシンプルですが、ちゃんと動作するか心配。

メモ

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