在其他语言中是否有与 Ruby 的 method_missing 等效的方法? [英] Are there equivalents to Ruby's method_missing in other languages?

查看:57
本文介绍了在其他语言中是否有与 Ruby 的 method_missing 等效的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,对象有一个名为 method_missing 的方便方法,它允许人们处理甚至尚未(明确)定义的方法的方法调用:

<块引用>

当 obj 收到它无法处理的消息时由 Ruby 调用.符号是被调用方法的符号,参数是传递给它的任何参数.默认情况下,调用此方法时解释器会引发错误.但是,可以覆盖该方法以提供更多动态行为.下面的例子创建了一个 Roman 类,它响应名称由罗马数字组成的方法,返回相应的整数值.

类罗马def romanToInt(str)# ...结尾def method_missing(methId)str = methId.id2nameromanToInt(str)结尾结尾r = Roman.newr.iv #=>4r.xxiii #=>23r.mm #=>2000年

例如,Ruby on Rails 使用它来允许调用诸如 find_by_my_column_name 之类的方法.

我的问题是,还有哪些其他语言支持 method_missing 的等效项,您如何在代码中实现等效项?

解决方案

method_missing 的一些用例可以在 Python 中使用 __getattr__ 实现,例如

class Roman(object):def roman_to_int(自我,罗马):# 在这里实现def __getattr__(self, name):返回 self.roman_to_int(name)

然后你可以这样做:

<预><代码>>>>r = 罗马()>>>静脉4

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:

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.

class Roman
 def romanToInt(str)
   # ...
 end
 def method_missing(methId)
   str = methId.id2name
   romanToInt(str)
 end
end

r = Roman.new
r.iv      #=> 4
r.xxiii   #=> 23
r.mm      #=> 2000

For example, Ruby on Rails uses this to allow calls to methods such as find_by_my_column_name.

My question is, what other languages support an equivalent to method_missing, and how do you implement the equivalent in your code?

解决方案

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

这篇关于在其他语言中是否有与 Ruby 的 method_missing 等效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆