python构造函数和默认值

Python constructor and default value

本问题已经有最佳答案,请猛点这里访问。

Somehow,in the node class below,the wordListand adjacencyListvariable is shared between all instances of node.

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> 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变量?

我用Python3.1.2。


可变的默认参数通常不会满足您的需要。相反,请尝试以下操作:

1
2
3
4
5
6
7
8
9
10
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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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作为哨兵值,并为每个实例提供自己的列表。


我会尝试:

1
self.wordList = list(wordList)

强制它复制而不是引用同一对象。


1
2
3
4
class Node:
    def __init__(self, wordList=None adjacencyList=None):
        self.wordList = wordList or []
        self.adjacencyList = adjacencyList or []