您可以使用functools.partial
>>> from functools import partial
>>> def my_function(a,b,c,d,e):
... print (a,b,c,d,e)
...
>>> func_with_defaults = partial(my_function, 1, 2, e=5)
>>> func_with_defaults(3, 4)
(1, 2, 3, 4, 5)
編輯:
既然你不提前擁有這些價值,你不能使用partial
或lambda
。 你可能會想這樣做:
>>> A = lambda x: x + y
>>> def do_something(y):
... return A(2) # hope it uses the `y` parameter...
...
>>> do_something(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in do_something
File "<stdin>", line 1, in <lambda>
NameError: global name 'y' is not defined
但你可以看到這是行不通的。爲什麼?因爲當你定義一個函數時,python會保存你定義它的範圍,並用它來解決變量。
如果你有機會訪問some_func
將有可能給你想要做什麼用「黑客」利用inspect
解釋堆棧但這不是做一個強大的也不優雅的事情,所以做不做到這一點。
我想你的情況做的就是重寫聲明。
如果你真的想避免這種情況,你可以使用exec
試一下:
>>> def some_function(a,b,c):
... print(a,b,c)
...
>>> code = 'some_function(a+b,c,%s)'
>>>
>>> def func_one(a,b, c):
... exec code % 1
...
>>> def func_two(a,b,c):
... exec code % 2
...
>>> func_one(1,2,3)
(3, 3, 1)
>>> func_two(1,2,3)
(3, 3, 2)
但這醜陋。
如果你只使用位置參數給你的函數,你可以做一些更優雅如:
>>> def compute_values(a,b,c):
... return (a+b, c)
...
>>> def func_one(a,b,c):
... some_function(*(compute_values(a,b,c) + (1,)))
...
>>> def func_two(a,b,c):
... some_function(*(compute_values(a,b,c) + (2,)))
...
>>> func_one(1,2,3)
(3, 3, 1)
>>> func_two(1,2,3)
(3, 3, 2)
但在這一點上你只是重複一個不同的文本,而你失去了很多的可讀性。 如果你想在Python中有預處理功能,你可以嘗試Python Preprocessing,儘管在你的情況下,我寧願重複函數調用。
我拉的東西從我的答覆到目前爲止起來這裏,所以這一切都在一個地方:我不能改變'some_func'的定義。問題似乎是這樣的:如果事情要在一次掃描中得到幫助,它必須在回調函數之外完成,但param1等僅在*之內變得可見。 C預處理器通過很愚蠢的做法:它不關心param2 + param1是什麼,它只是文本。 –