2

I have an issue in Python I couldn't believe to find out. See the following code:

class Container(object):
    array = []

    def __init__(self):
        print self.array

for i in range(0, 5):
    container = Container()
    container.array.append('Test')
print 'Last Container:', container.array

The output is:

[]
['Test']
['Test', 'Test']
['Test', 'Test', 'Test']
['Test', 'Test', 'Test', 'Test']
Last Container: ['Test', 'Test', 'Test', 'Test', 'Test']

I thought the Container class is initialized with the values at the top on instantiation. Why is this not the case?

Thank you!

4

3 回答 3

6

中的代码在class:创建类时执行,而不是在创建类的实例时执行。这是一个更清楚地表明这一点的示例:

>>> class Test(object):
...     print "Test"
...     def __init__(self):
...         print "init"
...
Test
>>> t = Test()
init

请注意,“Test”是在创建类时打印的,而不是在我创建 Test 对象时打印的。

正如其他答案所指出的那样,如果您希望属性对于类的特定实例(而不是类的所有实例)是本地的,则必须将代码放在__init__方法中:

def __init__(self):
    self.array = []
于 2012-06-10T17:51:45.687 回答
4

您直接放置在类定义中的任何属性都是类属性,因此Container.array在所有实例之间共享Container

如果您想要一个实例属性,请在以下self.array = []范围内设置__init__()

    def __init__(self):
        self.array = []
        print self.array
于 2012-06-10T17:48:06.057 回答
3

You should be instantiating the list in __init__ like so:

class Container(object):

    def __init__(self):
        self.array = []
        print self.array

Class variables defined at the top level of the class are created at runtime, so if they're mutable -- like a list or a dictionary -- you're going to have this problem when you change them. Attributes set in init are created when the class is instantiated, meaning you get a new list for each object.

于 2012-06-10T17:46:45.027 回答