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

时间:2014-11-24 17:47:09

标签: python function arguments

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

因此,对于myfunct_specific1,我正在运行a=10myfunct_specific2a=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

编辑(添加):

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'

1 个答案:

答案 0 :(得分: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)

以下是演示:

>>> 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
>>>
相关问题