Are there equivalents to Ruby's method_missing in other languages?

前端 未结 15 1630
渐次进展
渐次进展 2020-12-08 08:00

In Ruby, objects have a handy method called method_missing which allows one to handle method calls for methods that have not even been (explicitly) defined:

15条回答
  •  独厮守ぢ
    2020-12-08 08:37

    Some use cases of method_missing can be implemented in Python using __getattr__ e.g.

    class Roman(object):
      def roman_to_int(self, roman):
        # implementation here
    
      def __getattr__(self, name):
        return self.roman_to_int(name)
    

    Then you can do:

    >>> r = Roman()
    >>> r.iv
    4
    

提交回复
热议问题