使用关键字Args在Python中初始化,而无需在实例之间共享 [英] Initialising in Python using Keyword Args without sharing between instances
问题描述
如何在不使用类实例之间共享的情况下在初始化程序中使用关键字args?
How can I use keyword args in an initialiser without sharing it between instances of a class?
以下不良行为的示例,如果我要向集合foo
中添加任何内容,则将在这两种情况下都将其添加.
Example of the bad behaviour below, if I were to add anything to the set foo
then it would be added in both instances.
In [1]: class Klass:
def __init__(self, foo=set()):
self.foo = foo
In [2]: a = Klass()
In [3]: b = Klass()
In [4]: a.foo is b.foo
Out[4]: True
推荐答案
请注意,可变默认参数仅会出现此问题-请参见.要使用可变的默认参数,通常在函数定义中将默认值设置为None
,然后在函数内部检查是否已提供值:
Note that this issue will only occur with mutable default arguments - see "Least Astonishment" and the Mutable Default Argument. To use a mutable default argument, it is conventional to set the default to None
in the function definition, then check inside the function whether or not a value has been supplied:
class Klass:
def __init__(self, foo=None):
if foo is None:
foo = set()
self.foo = foo
或:
self.foo = foo if foo is not None else set()
请注意,None
是通过身份(if foo is None:
)进行测试的,而不是相等性(if foo == None:
)或真实性(if not foo:
)进行的测试.例如,如果您要显式传递已引用else的空集,则后者是一个问题.
Note that None
is tested by identity (if foo is None:
), not equality (if foo == None:
) or truthiness (if not foo:
). For example, the latter is an issue if you want to explicitly pass in an empty set you have referenced elsewere.
这篇关于使用关键字Args在Python中初始化,而无需在实例之间共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!