具有较少参数和可选参数的函数

use*_*487 3 python arguments function

我经常编写看起来像这样的代码,并且正在寻找更好的建议.基本上,我通常创建一些通用函数myfuc_general来处理我需要的所有参数,通常使用可选参数.但是,我经常运行2个(可能更多)特定功能.在这种情况下,除了其中一个参数不同之外,一切都是相同的a.我经常运行它们以至于我实际上更喜欢只有两个附加功能,所以我不必记住可选参数需要的内容.

因此myfunct_specific1,我正在跑步,a=10而且myfunct_specific2,a=20.还有比这更好的事情吗?这似乎很草率,如果我需要更改myfuct_general调用,它有缺点,然后我必须更改所有其他功能.

def myfunc_general(constant, a=1,b=2):
    return constant+a+b

def myfunct_specific1(constant,b=2):
    a=10
    return myfunc_general(constant,a,b=2)

def myfunct_specific2(constant,b=2):
    a=20
    return myfunc_general(constant,a,b=2)

print myfunct_specific1(3) #15
print myfunct_specific2(3) #25
Run Code Online (Sandbox Code Playgroud)

编辑(补充):

iCodez感谢您的建议.我有这种特殊情况,它给我一个错误.救命?再次感谢

def myfunc_general(constant, constant2, a=0,b=2):
    return constant+constant2+b+a

import functools
myfunct_specific=functools.partial(myfunc_general,constant2=30)

print myfunct_specific
print myfunct_specific(3,5,b=3)


Traceback (most recent call last):
  File "C:/Python27/test", line 8, in <module>
    print myfunct_specific(3,5,b=3)
TypeError: myfunc_general() got multiple values for keyword argument 'constant2'
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 5

您可以使用它functools.partial来简化:

from functools import partial

def myfunc_general(constant, a=1, b=2):
    return constant+a+b

myfunct_specific1 = partial(myfunc_general, a=10)
myfunct_specific2 = partial(myfunc_general, a=20)
Run Code Online (Sandbox Code Playgroud)

以下是演示:

>>> from functools import partial
>>>
>>> def myfunc_general(constant, a=1, b=2):
...     return constant+a+b
...
>>> myfunct_specific1 = partial(myfunc_general, a=10)
>>> myfunct_specific2 = partial(myfunc_general, a=20)
>>>
>>> print myfunct_specific1(3)
15
>>> print myfunct_specific2(3)
25
>>>
Run Code Online (Sandbox Code Playgroud)