我试图找到一个类似的问题/答案,但努力把任何答案到这个问题,希望有人可以帮助。
我有一个函数,它读取文件名data_dir/filename
,从文件中提取data_var
,并且还读取**kwargs
中的其他参数。必须读入默认的filename
和dat_var
,函数看起来像
def function(data_dir, filename, data_var, **kwargs):
# some code
然而,我想要添加filename2
和data_var2
的选项,这也必须伴随着**kwargs
来计算额外的数据。
kwargs = {"lflag" : True}
并读入额外的数据,该函数看起来像
def function(data_dir, filename, data_var, filename2, data_var2, **kwargs):
# default flag
opt_dic = {"lflag" : False}
for key in kwargs:
opt_dic[key] = kwargs[key]
# load in filename and read data_var
ds = Dataset(data_dir + filename)
var = ds.variables[data_var][...]
ds.close()
# load in filename2 and read data_var2
if opt_dic["lflag"]:
ds2 = Dataset(data_dir + filename2)
var2 = ds2.variables[data_var2][...]
ds2.close()
# some more code
但是我如何将filename2
和data_var2
定义为可选参数,可以在不需要时离开函数?
在默认状态下调用该函数的示例,
kwargs = {}
output = function(data_dir, filename, data_var, **kwargs):
和附加数据
kwargs = {"lflag" : True}
output = function(data_dir, filename, data_var, filename2, data_var2, **kwargs):
考虑在任何情况下只使用一个filename
和一个data_var
参数。因此,各自的参数可以是字符串或两个字符串的列表。例如,为filename
实现这个想法可以这样开始:
def function(data_dir, filename, data_var, **kwargs):
filename2 = None
if type(filename) == list:
if len(filename) != 2:
raise ValueError('filename lists must have exactly two elements.')
filename, filename2 = filename
print(filename, filename2)
# ...
function('/a/', ['f1', 'f2'], 'v1')
>>> f1 f2
*args和* *kwargs
def function(data_dir, filename, data_var, *args, **kwargs)
data_dir = "method argument"
filename = "method argument"
data_var = "method argument"
args = [] # an iterable
kwargs = {} # a dictionary key/value pair
print(data_dir, filename, data_var)
print(args)
print(kwargs)
输出示例>>> function("/tmp", "test.txt", "var-test", "test2.txt", "var2-test", test="arguments-keyvalue")
/tmp test.txt var-test
('test2.txt', 'var2-test')
{'test': 'arguments-keyvalue'}
Real Python explain: here
您不需要kwargs标志;你可以按照
这样做def function(data_dir, filename, data_var, filename2=None, data_var2=None):
# always perform computations on data_dir and filename
ds = Dataset(data_dir + filename)
var = ds.variables[data_var][...]
ds.close()
# if filename2 was passed, assume data_var2 was passed
if not (filename2 is None):
ds2 = Dateset(data_dir + filename)
var2 = ds2.variables[data_var2][...]
# some more code
...
这里有一个最小的例子来演示
def f(x,y=None)
print(x) # always executed
if not(y is None):
print(y)
f(1) # prints 1
f(1,2) # prints 1 and 2, separated by newlines
<代码>代码>