如何基于以前的参数定义默认参数值? [英] How to define default argument value based on previous arguments?
问题描述
我想定义一个 resize(h,w)
方法,并且希望能够通过以下两种方式之一调用它:
I want to define a resize(h, w)
method, and I want to be able to call it in one of two ways:
-
调整大小(x,y)
-
resize(x)
resize(x,y)
resize(x)
在第二个调用中,我要 y
等于 x
。我可以在方法定义中执行此操作吗?还是应该执行类似 resize(x,y = None)
的操作并检入内部内容:
Where, in the second call, I want y
to be equal to x
. Can I do this in the method definition or should I do something like resize(x,y=None)
and check inside:
if y is None:
y = x
推荐答案
我可以在方法定义中做到这一点
Can I do this in the method definition
没有在方法定义期间,无法知道 x
在运行时可能具有什么值。默认参数在定义时进行一次评估,无法为 y
保存动态值。
No. During the method definition there's no way to know what value x
might have at run-time. Default arguments are evaluated once at definition time, there's no way to save a dynamic value for y
.
还是我应该做类似
resize(x,y = None)
的操作并检查内部
完全正确。这是Python中的常见用法。
exactly. This is a common idiom in Python.
这篇关于如何基于以前的参数定义默认参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!