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

2023-11-29

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

有什么方法可以继续使用构造函数参数的默认值(在本例中为空列表),但同时获取两者a and b拥有自己的wordList and adjacencyList变量?

我正在使用 python 3.1.2。


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

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 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python构造函数和默认值[重复] 的相关文章

随机推荐