将变量作为函数的参数

问题描述 投票:1回答:1

因此,我需要使用变量(n)作为另一个函数(参数)的默认值。

def fit(X_train,Y_train):
   df=pd.DataFrame(np.column_stack((X_train, Y_train)))
   global n
   var=parameters()
   n = df.shape[1] - 1

我想使用'n'的值作为下面给出的函数'parameter'的参数,作为默认参数。我必须将全局变量声明为n = 0,否则,将显示错误消息,说明未定义名称n。

def parameters(degree = 1, nof = n):
   global d
   d=degree
   f=n
   nof=f
   return nof

Now 'f'始终具有来自函数fit的n值。因此,每当我在调用函数参数nof时放置另一个nof值时,其自身就会更改为n的值。我希望仅当用户未为nof指定任何值时,nof的值才为'n'。有什么办法吗?

python function arguments parameter-passing
1个回答
0
投票

默认值在声明函数时设置,而不是在运行时设置。修改变量时,这可能导致令人惊讶的行为:

n = 1

def parameters(nof = n):  # The default argument is n, but...
   return nof

n = 5

print(parameters())  # This prints 1, not 5!

不是将默认变量设置为n,更安全的是仅在函数运行时使用None作为占位符来应用默认值:

def parameters(nof = None):
    if nof is None:
        nof = n  # The 'global' keyword isn't necessary, but you can include it to be explicit

    return nof

或者,如果仅在parameters函数内部使用fit函数,则可以使其成为内部函数,以避免处理全局变量。此内部函数将自动访问外部函数的范围:

def fit():
   n = 0  # Not global scoped

   def parameters(nof = None):
       if nof is None:
           nof = n  # This is the same 'n' defined above
       return nof

   var = parameters()  # This returns 0
   n = 1
   var = parameters()  # This returns 1
© www.soinside.com 2019 - 2024. All rights reserved.