Python 构造函数和默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4841782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python constructor and default value
提问by Hery
Somehow, in the Node class below, the wordListand adjacencyListvariable is shared between all instances of Node.
不知何故,在下面的 Node 类中,wordListandadjacencyList变量在 Node 的所有实例之间共享。
>>> class Node:
... def __init__(self, wordList = [], adjacencyList = []):
... self.wordList = wordList
... self.adjacencyList = adjacencyList
...
>>> a = Node()
>>> b = Node()
>>> a.wordList.append("hahaha")
>>> b.wordList
['hahaha']
>>> b.adjacencyList.append("hoho")
>>> a.adjacencyList
['hoho']
Is there any way I can keep using the default value (empty list in this case) for the constructor parameters but to get both aand bto have their own wordListand adjacencyListvariables?
有什么办法,我可以继续使用默认值(在这种情况下空单)构造函数的参数,但要同时获得a,并b有自己wordList和adjacencyList变量?
I am using python 3.1.2.
我正在使用 python 3.1.2。
采纳答案by Michael J. Barber
Mutable default arguments don't generally do what you want. Instead, try this:
可变的默认参数通常不会做你想要的。相反,试试这个:
class Node:
def __init__(self, wordList=None, adjacencyList=None):
if wordList is None:
self.wordList = []
else:
self.wordList = wordList
if adjacencyList is None:
self.adjacencyList = []
else:
self.adjacencyList = adjacencyList
回答by krousey
I would try:
我会尝试:
self.wordList = list(wordList)
to force it to make a copy instead of referencing the same object.
强制它制作一个副本而不是引用同一个对象。
回答by aaronasterling
Let's illustrate what's happening here:
让我们来说明这里发生了什么:
Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
... def __init__(self, x=[]):
... x.append(1)
...
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)
You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults.
您可以看到默认参数存储在一个元组中,该元组是相关函数的一个属性。这实际上与所讨论的类无关,适用于任何功能。在 python 2 中,属性将为func.func_defaults.
As other posters have pointed out, you probably want to use Noneas a sentinel value and give each instance it's own list.
正如其他海报所指出的那样,您可能希望将其None用作哨兵值并为每个实例提供自己的列表。
回答by Shankar Cabus
class Node:
def __init__(self, wordList=None adjacencyList=None):
self.wordList = wordList or []
self.adjacencyList = adjacencyList or []

