在Python 3.3.3,當我嘗試在Python中,是否有更簡單的方法使一個參數默認爲另一個參數?
def f(x,y=0):
z = x+y
return z
它工作得很好。
然而,當我嘗試
def f(x,y=x):
z = x+y
return z
我得到NameError: name 'x' is not defined
。
我知道我可能只是做
def f(x,y=None):
y = x if y is None else y
z = x+y
return z
。
是否有更簡潔或更好的方式來獲得所需的結果?
這太可怕了。你採取了一些簡單的措施,使其變得不必要的複雜。 – dstromberg
忘了提及'lambda x,y = None:x + [y,x] [y是None]'。 – Hyperboreus