如何在Python中声明函数中的可选参数(mode)(非可选,mode=";bla-bla";)?
如何在函数中声明一个可选参数,该函数在Python中至少接受一个实(非可选)参数 下面是一个例子:如何在Python中声明函数中的可选参数(mode)(非可选,mode=";bla-bla";)?,python,argument-passing,function-declaration,Python,Argument Passing,Function Declaration,如何在函数中声明一个可选参数,该函数在Python中至少接受一个实(非可选)参数 下面是一个例子: def myfunc(data, mode='never_mind'): if mode == 'never_mind: return elif mode == 'print': print "Input data:", data # do something with data... elif mode == 'sqrt'
def myfunc(data, mode='never_mind'):
if mode == 'never_mind:
return
elif mode == 'print':
print "Input data:", data
# do something with data...
elif mode == 'sqrt':
print "%f is a square root of %f (input data)" % (data ** 0.5, data)
else:
print "Invalid input mode."
# I want to declare a new function as myfunc() with predeclared mode='sqrt' (for example).
# How can I do it?
new_func = myfunc
new_func.mode = 'sqrt' # it doesn't work!
# or...
new_func = myfunc(mode='sqrt') # it doesn't work either!
签出
functools.partial
In [1]: from functools import partial
In [2]: def f(a, b="b"):
...: print(a, b)
...:
In [3]: g = partial(f, b="c")
In [4]: g("a")
a c