【发布时间】:2018-12-03 02:58:42
【问题描述】:
我想编写一个函数,其中一个参数的默认值是传递给同一函数的一些参数的函数。像这样的:
def function(x, y = function2(x)):
##definition of the function
是否可以在 Python 中编写这样的函数? 我遇到了this c++ 的答案。但是Python中没有方法重载
提前致谢。
【问题讨论】:
我想编写一个函数,其中一个参数的默认值是传递给同一函数的一些参数的函数。像这样的:
def function(x, y = function2(x)):
##definition of the function
是否可以在 Python 中编写这样的函数? 我遇到了this c++ 的答案。但是Python中没有方法重载
提前致谢。
【问题讨论】:
解决此问题的一种非常常用的方法是使用None 作为占位符:
def function(x, y=None):
if y is None:
y = f2(x)
pass # whatever function() needs to do
【讨论】:
这毫无意义。你想达到什么目标? Y是什么?是函数吗?那么你必须写:
def function(x, y = function2):
##definition of the function
如果 Y 是一个简单的值,那么你必须写:
def function(x, y = None):
if y is None:
y = function2(x)
【讨论】:
我不知道你究竟想在这里实现什么用例,但你可以使用装饰器来满足你的需求。
这里有一个愚蠢的例子https://repl.it/@SiddharthShishu/IntrepidPunctualProspect
【讨论】:
def function(x, y=None):
if y is None:
y = f2(x)
【讨论】: