def foo(arg1, arg2, **config):
# config now contains any keyword arguments passed to foo
并称之为:
foo(1, 2, some="key", another="value")
# or if you have a hash from elsewhere
foo(1, 2, **{"some": "key", "another": "value"})
在Ruby中,类似的构造是这样实现的:
def foo(arg1, arg2, config={})
# config is *still* a positional argument even though it has a default value!
# do stuff with your configuration hash
# as if it were a dictionary of keyword args
# for example:
default_config = {:options {:key => 'value'}, :stuff => 123}
config = default_config.merge(config)
end
它的名字是这样的:
foo(1, 2, :some => 'key', :another => 'value')
# which translates into
foo(1, 2, {:some => 'key', :another => 'value'})
# the {} are optional for the last argument
如果我们将Ruby代码直接翻译成Python,它会像这样:
def foo(arg1, arg2, config=None):
# This is not *quite* exact because we can still call `foo(1, 2, config={})`
# but I think it is as close as you can get in Python
if config is None:
config = {}
# Now we can do things with the config dictionary.
你可以称之为:
# Note: no ** (splat) operator in front of our dictionary
foo(1, 2, {"some": "key", "another": "value"})
编辑:Ruby2.0引入了splat操作符和关键字参数,因此如果您使用的是Ruby>;=2.0,那么只需使用
foo(arg, keyword: arg_default)
和foo(1, **{:keyword => arg})
。如果您使用的是Ruby 1.x,那么以下内容适用:Ruby1.x没有用于关键字参数的splat操作符(事实上,Ruby1.x甚至没有关键字参数)。相反,只需将
config
作为最后一个参数,函数的用户就可以传入一个哈希,从中提取密钥:在Python中,您可以这样定义
foo
和bar
:并称之为:
在Ruby中,类似的构造是这样实现的:
它的名字是这样的:
如果我们将Ruby代码直接翻译成Python,它会像这样:
你可以称之为:
相关问题 更多 >
编程相关推荐