不知何故,在下面的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
和b
拥有其自身的变量wordList
以及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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句