Python构造函数和默认值

167 投票
4 回答
305483 浏览
提问于 2025-04-16 10:53

在下面的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']

有没有办法让我继续使用构造函数参数的默认值(在这个例子中是空列表),同时让各自拥有自己的wordListadjacencyList变量呢?

我使用的是python 3.1.2。

4 个回答

28

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这时候,我们可以去一些技术论坛,比如StackOverflow,去寻找解决方案或者向其他人请教。在这些论坛上,很多人会分享他们的经验和解决办法,帮助我们更好地理解问题。

当你在这些论坛上提问时,记得描述清楚你的问题,包括你遇到的错误信息、你使用的代码,以及你尝试过的解决方法。这样,其他人才能更容易地理解你的问题,并给出有效的建议。

总之,技术论坛是一个很好的资源,可以帮助我们解决编程中的各种问题。只要我们善于利用这些资源,就能不断提高自己的编程能力。

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

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

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

你可以看到,默认参数被存储在一个元组里,这个元组是相关函数的一个属性。其实这和类没有关系,任何函数都是这样。在 Python 2 中,这个属性叫做 func.func_defaults

正如其他人提到的,你可能想用 None 作为一个特殊值,并给每个实例一个自己的列表。

188

可变的默认参数通常不会按你想要的那样工作。所以,试试这个方法:

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 

撰写回答