mrkn / pycall.rb

Calling Python functions from the Ruby language
MIT License
1.06k stars 75 forks source link

Reflect subclass in Python #59

Open kou opened 6 years ago

kou commented 6 years ago

We need to define new Ruby-level methods to both superclass and subclass for Python classes that they are superclass and subclass relation.

Here is an example.

A is a superclass.

B is a subclass of A.

/tmp/x.py:

class A:
    pass

class B(A):
    pass

I want to define a Ruby method to A and B by defining only one Ruby method to A (superclass). But A and B in Ruby aren't superclass and subclass relation. So I need to define two Ruby methods to both A and B.

/tmp/a.rb:

require "pycall"

PyCall.sys.path.append("/tmp")

x = PyCall.import_module("x")

A = x.A
B = x.B

class A
  register_python_type_mapping
  def xxx
    p [self.class, :A, :xxx]
  end
end

A.new.xxx

# class B
#   register_python_type_mapping
#   def xxx
#     p [self.class, :B, :xxx]
#   end
# end

# Actual: undefined method `xxx' for <x.B object at 0x7f415ce6e668>:B (NoMethodError)
# Expected: A#xxx is called
B.new.xxx