不知何故,在下面的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.
test.py中的代码:
class Base(object):
    def __init__(self, l=[]):
        self.l = l
    def add(self, num):
        self.l.append(num)
    def remove(self, num):
        self.l.remove(num)
class Derived(Base):
    def __init__(self, l=[]):
        super(Derived, self).__init__(l)
Python shell会话:
Python 2.6.5 (r265:79063, Apr  1 2010, 05:22:20) 
[GCC 4.4.3 20100316 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> a = test.Derived()
>>> b = test.Derived()
>>> a.l
[]
>>> b.l
[]
>>> a.add(1)
>>> a.l
[1]
>>> b.l
[1]
>>> c = test.Derived()
>>> c.l
[1] …我一直在努力理解Python对类和实例变量的处理.特别是,我发现这个答案很有帮助.基本上它说如果你声明一个类变量,然后你做一个赋值[instance].property,你将完全分配一个不同的变量 - 一个与类变量不同的命名空间.
所以我考虑过 - 如果我希望我的类的每个实例都有一个默认值(比如零)的成员,我应该这样做:
class Foo:
    num = 0
或者像这样?
class Foo:
    def __init__(self):
        self.num = 0
基于我之前读过的内容,我认为第二个例子是初始化'right'变量(实例而不是类变量).但是,我发现第一种方法也非常有效:
class Foo:
    num = 0
bar = Foo()
bar.num += 1 # good, no error here, meaning that bar has an attribute 'num'
bar.num
>>> 1
Foo.num
>>> 0 # yet the class variable is not modified! so what 'num' did I add to just now?
那么..为什么这个有效?我得不到什么?FWIW,我之前对OOP的理解来自C++,因此通过类比(或指向它发生故障)的解释可能是有用的.
我正在设置一个类,并且第一步使用__init__函数来初始化属性。但是,当我尝试从该类创建实例时,它显示AttributeError。
我已经一遍又一遍地检查代码,看语法是否有问题,但错误仍然存在
class RandomWalk():
    def ___init___(self, points = 10):
        """initialize attributes of a walk"""
        self.points = points
        self.x_values = [0]
        self.y_values = [0]
rw = RandomWalk()
print(rw.points)
我期望输出10作为默认值points,但错误显示:
Traceback (most recent call last):
  File "test1.py", line 10, in <module>
    print(rw.points)
AttributeError: 'RandomWalk' object has no attribute 'points'
如果我用或替换属性points,问题仍然存在x_valuesy_values