Python构造函数和默认值 [英] Python constructor and default value

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

问题描述

以某种方式,在下面的Node类中,在所有Node实例之间共享 wordList 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']

有什么方法可以继续使用构造函数参数的默认值(在这种情况下为空列表),但要同时获取 a b wordList adjacencyList 变量?

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?

我正在使用python 3.1.2。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆