[英]Sets the default value of a parameter based on the value of another parameter
所以我想創建一個函數,生成從“開始”到“結束”與“大小”一樣多的連續數字。 對於迭代,它將在函數內部計算。 但我無法設置參數“end”的默認值。 在我進一步解釋之前,這是代碼:
# Look at this -------------------------------
# ||
# \/
def consecutive_generator(size=20, start=0, end=(size+start)):
i = start
iteration = (end-start)/size
arr = []
temp_size = 0
while temp_size < size:
arr.append(i)
i += iteration
temp_size += 1
return arr
# with default end, so the 'end' parameter will be 11
c1= consecutive_generator(10, start=1)
print(c1)
# with end set
c2= consecutive_generator(10, end=20)
print(c2)
上面可以看出(關於'end'參數的默認值),我要實現的是'end'參數,其默認值為'start' + 'size'參數(那么迭代將是1)
輸出肯定會出錯。 那么我該怎么做呢? (這是我第一次在 stackoverflow 上提問,如果我犯了錯誤,請見諒)
(關閉)
這是一個非常標准的模式:
def consecutive_generator(size=20, start=0, end=None):
if end is None:
end = size + start
根據 Python 的文檔,
執行函數定義時,從左到右計算默認參數值。
因此,不能從函數調用時傳遞的其他動態值評估參數的默認值。
您應該使用像None
這樣的可區分值作為默認值。 然后您可以檢查它並動態評估正確的默認值。 例如,
def consecutive_generator(size=20, start=0, end=None):
if end is None:
end = size + start
...
如果您需要None
作為從調用者傳遞的有效值,您可以使用其他對象或其他東西來區分有效值。
default_end = object()
def consecutive_generator(size=20, start=0, end=default_end):
if end is default_end:
end = size + start
...
默認方式正如 Samwise 所說,但有一個替代解決方案可能同樣有效。
def consecutive_generator(size=20, start=0, **kwargs):
end = kwargs.get('end', size+start)
此方法允許您在 end 存在時獲取它,或者在 end 不存在時簡單地設置它的值。
要調用它,如果要將其設置為默認值以外的其他值,則此方法確實需要指定函數調用的參數end
。
consecutive_generator(20, 0, end=50)
也許考慮查看range和numpy.linspace的文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.