Python构造函数和默认值

标签 python constructor default-value

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

我正在使用 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构造函数和默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4841782/

相关文章:

python - 如何访问 numpy recarray 的字段#k?

C# - 只读属性和字段不能在派生类构造函数中设置

C++ 如何给抽象类中的成员变量一个默认值?

MySQL 默认值为 NULL

如果请求值为空,Laravel 设置默认值

python - 如何让我的 Spyder 代码在 GPU 而不是 Ubuntu 上的 cpu 上运行?

python - Python 3 中的 re.findall

python - 在 pandas 中,如何在数据框中显示最常见的诊断,但只计算每个患者出现 1 次相同的诊断

c++ - 隐式构造函数转换的编译器优化

Matlab类方法错误