Python的构造函数和默认值

不知何故,在下面的Node类中,wordList和adjacencyListvariables在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和adjacencyListvariables?

我正在使用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 

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

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

你可以看到默认参数存储在一个元组中,这个元组是所讨论的函数的一个属性。 这实际上与课堂上没有任何关系,并没有任何function。 在Python 2中,该属性将是func.func_defaults

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

我会尝试:

 self.wordList = list(wordList) 

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

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