在下面的Node类中,wordList和adjacencyList变量在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变量之外,我有没有办法继续使用构造函数参数的默认值(在本例中为空列表)?
我使用的是python 3.1.2。
发布于 2011-01-30 16:06:37
可变的默认参数通常不会做你想要的事情。相反,试着这样做:
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 发布于 2011-01-30 16:14:07
让我们来说明一下这里发生了什么:
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],)您可以看到,默认参数存储在一个元组中,该元组是相关函数的一个属性。这实际上与所讨论的类无关,适用于任何函数。在Python2中,该属性将为func.func_defaults。
正如其他发帖者所指出的那样,您可能希望使用None作为前哨数值,并为每个实例提供其自己的列表。
发布于 2013-02-06 06:11:43
class Node:
    def __init__(self, wordList=None adjacencyList=None):
        self.wordList = wordList or []
        self.adjacencyList = adjacencyList or []https://stackoverflow.com/questions/4841782
复制相似问题