簡體   English   中英

函數中帶有默認參數的 TypeError - Python

[英]TypeError with default parameters in a function - Python

我試圖創建一個帶有 6 個參數的函數,其中 3 個是“可選的”,因為我嘗試給它們提供默認值。 該函數接收 6 個值並將它們提供給另一個函數(之前定義)。

每次我嘗試運行它時,我都會得到一個TypeError: Coeff() got an unexpected keyword argument 'h' 我希望有人可以幫助我解決這個問題!

def TSR_inf(coeff, maxmin, d, h='houle', t_h=0, Per=0):

   coeff = coeff
   maxmin = maxmin
   d=d
   h = h
   t_h = t_h
   Per = Per

   Coeff(coeff, maxmin, d, h='houle', t_h=0, Per=0)

Coeff()函數定義如下:

def Coeff(coeff, maxmin, d, h='houle', t_h=0, Per=0):

  if coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 0 and Per == 0 and h == 'houle':
      Wave_max('x')
  elif coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 0 and Per == 0 and h == 'no houle':
      Wave_max('x', 'no houle')
  elif coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 'reg' and Per == 0 and h == 'houle':
      Wave_max('x', 'reg')
  elif coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 'reg' and Per == 1 and h == 'houle':
      Wave_max('x', 'reg', 1)
  elif coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 'reg' and Per == 1.5 and h == 'houle':
      Wave_max('x', 'reg', 1.5)
  elif coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 'reg' and Per == 2 and h == 'houle':
      Wave_max('x', 'reg', 2)
  elif coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 'irreg' and Per == 0 and h == 'houle':
      Wave_max('x', 'reg')
  elif coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 'irreg' and Per == 1 and h == 'houle':
      Wave_max('x', 'reg', 1)
  elif coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 'irreg' and Per == 1.5 and h == 'houle':
      Wave_max('x', 'reg', 1.5)
  elif coeff == 'wave' and maxmin == 'max' and d == 'x' and t_h == 'irreg' and Per == 2 and h == 'houle':
      Wave_max('x', 'reg', 2)

這個Coeff()函數調用了另一個函數def Wave_max(d, h, t_h, Per):我不會在這里發布,因為它無關緊要(但如果你確實想要它,請告訴我,我稍后會添加它)。

如果有人能發現我在哪里犯了導致TypeError的錯誤,我將不勝感激!

大家干杯! (提前謝謝你!)

發生這種情況是因為Coeff函數中的參數名稱是h並且沒有參數稱為h1 ,因為錯誤正確地指出了這一點。

您可能想要在TSR_inf函數的末尾執行類似Coeff(coeff1, maxmin1, d1, h=h1, t_h=t_h1, Per=Per1)的操作。

當您傳遞關鍵字參數時,始終使用與函數定義中使用的參數名稱相同的參數名稱,問題是您的函數參數是h='houle', t_h=0, Per=0並且您使用h1='houle', t_h1=0, Per1=0調用函數h1='houle', t_h1=0, Per1=0

您的實際函數調用應該是:

Coeff(coeff1, maxmin1, d1, h='houle', t_h=0, Per=0)

或者你已經在變量中遍歷了它們

Coeff(coeff1, maxmin1, d1, h=h1, t_h=t_h1, Per=Per1)

如果您想在Coeff函數中使用 h1 作為關鍵字參數,您可以將函數定義更改為

 def  Coeff(coeff1, maxmin1, d1, h='houle', t_h=0, Per=0, **kwargs)

並在函數中使用 h1 作為

kwargs.get('h1')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM