Python构造函数和默认值

2024-04-25 06:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

不知怎的,在下面的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变量?

我正在使用Python3.1.2。


Tags: 实例方法selfnode列表initdef函数参数
3条回答

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

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 

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

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

可以看到,默认参数存储在tuple中,tuple是所讨论函数的属性。这实际上与所讨论的类无关,而且与任何函数都无关。在python 2中,属性将是func.func_defaults

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

我会尝试:

self.wordList = list(wordList)

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

相关问题 更多 >