将默认参数定义为全局变量

将默认参数定义为全局变量

本文介绍了将默认参数定义为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Python函数 foo ,它接受一个默认参数,其中默认值设置为某个全局变量。如果我现在在调用该函数之前更改该全局变量,那么默认参数仍设置为该全局变量的原始值。



例如:

  x = 1 

def foo(a = x):
打印

x = 2
foo()

打印 1 ,而不是 2



我应该如何编写我的代码,以便我可以改变这个全局变量,并让它更新这个默认参数?

解决方案

默认变量仅被评估和设置一旦即可。所以Python会复制引用,并且从此开始,它始终将该引用作为默认值传递。您可以使用另一个对象作为默认对象,然后使用<$ c $>来解决此问题。

c> if 语句来相应地替换它。例如:

   the_default = object() 
x = 1

def foo(a = the_default ):
如果 the_default:
a = x
打印

x = 2
foo()

请注意,我们使用 is 执行引用平等。所以我们检查它是否确实是 default_object 。你不应该在代码的其他地方使用 the_default 对象。

在许多Python代码中,它们使用 None 作为默认值(并因此减少构造对象的数量)。例如:

  def foo(a = ):
如果a 无:
a = x
打印a

请注意,如果您这样做,你的程序不能区分用户调用 foo() foo(None),而使用某些东西因为 the_object 使得用户难以获得对该对象的引用。如果 None 也是一个有效的候选者,那么这很有用:如果你想要 foo(None)来打印'无'而不是 x


Suppose I have a Python function foo which takes a default argument, where that default is set to some global variable. If I now change that global variable before calling the function, the default argument is still set to the original value of that global variable.

For example:

x = 1

def foo(a=x):
    print a

x = 2
foo()

This prints 1, instead of 2.

How should I be writing my code, so that I can change this global variable, and have it update this default argument?

解决方案

A default variable is only evaluated and set once. So Python makes a copy of the reference and from then on, it always passes that reference as default value. No re-evaluation is done.

You can however solve this by using another object as default object, and then use an if statement to substitute it accordingly. Something like:

the_default = object()
x = 1

def foo(a = the_default):
    if a is the_default:
        a = x
    print a

x = 2
foo()

Note that we use is to perform reference equality. So we check if it is indeed the default_object. You should not use the the_default object somewhere else in your code.

In many Python code, they use None as a default (and thus reduce the number of objects the construct). For instance:

def foo(a = None):
    if a is None:
        a = x
    print a

Note however that if you do that, your program cannot make a distinction between a user calling foo() and foo(None) whereas using something as the_object makes it harder for a user to obtain a reference to that object. This can be useful if None would be a valid candidate as well: if you want foo(None) to print 'None' and not x.

这篇关于将默认参数定义为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:19