2

我正在编写我的第一个 python 程序,我遇到了一些看起来很奇怪的东西。

我的程序如下所示:

def main():
  listOfThings = []
  for i in range(0,3):
    newThing = thing()
    newThing.listOfStrings.append('newString')
    listOfThings.append(newThing)

事情看起来像这样:

class thing:
  listOfStrings = []

我期待 listOfThings 是:

listOfThings
 -thing1
  -newString
 -thing2
  -newString
 -thing3
  -newString

但相反,我得到了这个:

listOfThings
 -thing1
  -newString
  -newString
  -newString
 -thing2
  -newString
  -newString
  -newString
 -thing3
  -newString
  -newString
  -newString

在其他语言中,如果 thing.listOfStrings 是静态的,这就是我希望看到的。我在这里缺少一些python的微妙之处吗?

4

2 回答 2

4

listOfStrings是一个类属性。所有实例将共享相同的list

相反,您应该在__init__

class thing:
    def __init__(self):
        self.listOfStrings = []
于 2012-09-16T06:35:37.367 回答
4

In Python, any "variables" declared at class scope become class attributes, which are akin to static class members in other languages. They can be accessed either through the class name thing.listOfStrings or an instance newThing.listOfStrings, but they always refer to the same attribute.

If you want instance attributes, create them in an __init__ method:

class Thing:
    def __init__(self):
        self.listOfStrings = []

Every time you instantiate a new instance of Thing using Thing(), the __init__ will run in the new instance and give it its own listOfStrings list.

Note that due to Python's dynamic nature, __init__ is not the only place where instance attributes can be added (though it is the recommended location). For example, the following is legal:

class Foo:
    pass # empty class definition

a = Foo()
a.x = 42
print a.x # prints 42

b = Foo()
b.y = 99
print b.x # raises AttributeError
print b.y # prints 99
于 2012-09-16T06:43:36.190 回答