如何在Python中声明函数中的可选参数(mode)(非必需,mode="bla bla")?

2024-09-29 01:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在函数中声明一个可选参数,在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':
        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!

Tags: newinputdata参数modewithitsqrt
1条回答
网友
1楼 · 发布于 2024-09-29 01:27:05

签出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

相关问题 更多 >