构造函数和默认值

构造函数和默认值

本文介绍了Python 构造函数和默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知何故,在下面的 Node 类中,wordListadjacencyList 变量在 Node 的所有实例之间共享.

>>>类节点:... def __init__(self, wordList = [], adjacencyList = []):... self.wordList = wordList... self.adjacencyList = adjacencyList...>>>a = 节点()>>>b = 节点()>>>a.wordList.append("哈哈哈")>>>b.wordList['哈哈哈']>>>b.adjacencyList.append("hoho")>>>a.邻接表['呵呵']

有什么办法可以继续使用构造函数参数的默认值(在这种情况下为空列表),但要让 ab 都有自己的wordListadjacencyList 变量?

我使用的是 python 3.1.2.

解决方案

可变默认参数通常不能满足您的要求.相反,试试这个:

类节点:def __init__(self, wordList=None, adjacencyList=None):如果 wordList 为 None:self.wordList = []别的:self.wordList = wordList如果 adjacencyList 为 None:self.adjacencyList = []别的:self.adjacencyList = adjacencyList

Somehow, in the Node class below, the wordList and adjacencyList variable is shared between all instances of 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']

Is there any way I can keep using the default value (empty list in this case) for the constructor parameters but to get both a and b to have their own wordList and adjacencyList variables?

I am using python 3.1.2.

解决方案

Mutable default arguments don't generally do what you want. Instead, try this:

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 构造函数和默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 09:56