Python构造函数和默认值[重复]

问题描述 投票:94回答:4

这个问题在这里已有答案:

不知何故,在下面的Node类中,wordListadjacencyList变量在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']

有没有什么方法可以继续使用默认值(在这种情况下为空列表)的构造函数参数,但要让ab拥有自己的wordListadjacencyList变量?

我正在使用python 3.1.2。

python constructor default-value
4个回答
120
投票

可变默认参数通常不会执行您想要的操作。相反,试试这个:

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 

29
投票

让我们来说明这里发生了什么:

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],)

您可以看到默认参数存储在元组中,元组是相关函数的属性。这实际上与所讨论的类无关,适用于任何功能。在python 2中,属性将是func.func_defaults

正如其他海报所指出的那样,您可能希望使用None作为哨兵值,并为每个实例提供自己的列表。


17
投票
class Node:
    def __init__(self, wordList=None adjacencyList=None):
        self.wordList = wordList or []
        self.adjacencyList = adjacencyList or []

16
投票

我会尝试:

self.wordList = list(wordList)

强制它制作副本而不是引用同一个对象。

© www.soinside.com 2019 - 2024. All rights reserved.