gpt4 book ai didi

programming-languages - 有其他语言中的Ruby的method_missing等效项吗?

转载 作者:行者123 更新时间:2023-12-03 11:43:52 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

class Roman(object):
def roman_to_int(self, roman):
# implementation here

def __getattr__(self, name):
return self.roman_to_int(name)

然后,您可以执行以下操作:
>>> r = Roman()
>>> r.iv
4

关于programming-languages - 有其他语言中的Ruby的method_missing等效项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2865865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com