通过我的几个Python项目,我一直想知道什么是最有效的,同时又是一种向方法发送多个参数的美妙方式。
假设我们有一个方法接受以下参数foo,bar,spoot,rick,astley,无论数量,类型和关系。
根据你的说法,最有效率,pythonic和优雅的方式是什么?
简单参数参数:
def my_func(foo, bar, spoot, rick, astley):
# Do some stuff
my_func(foo, bar, spoot, rick, astley)
通过元组:
def my_func(some_tuple):
foo, bar, spoot, rick, astley = some_tuple
# Do some stuff
my_func((foo, bar, spoot, rick, astley))
使用相关元组和单个参数的简单参数:
def my_func(related_parameters_tuple, other_related_parameters_tuple, spoot):
foo, bar = related_parameters_tuple
rick, astley = other_related_parameters_tuple
# Do some stuff
my_func((foo, bar), (rick, astley), spoot)
字典:
def my_func(dictionary):
# Do some stuff
# dictionary['foo']
# dictionary['bar']
# ...
my_func({
'foo': foo,
'bar': bar,
'spoot': spoot,
'rick': rick,
'astley': astley
})
相关词典和单个参数的简单参数:
def my_func(related_parameters_dictionary, other_related_parameters_dictionary, spoot):
# Do some stuff
# related_parameters_dictionary['foo']
# related_parameters_dictionary['bar']
# other_related_parameters_dictionary['rick']
# other_related_parameters_dictionary['astley']
# ...
my_func({
'foo': foo,
'bar': bar,
'spoot': spoot,
'rick': rick,
'astley': astley
})
感谢您分享您的意见!