0

我有一个关于在 Python中使用self变量的问题。请看下面的例子:

from copy import deepcopy
class IntClass:
    props = {}
    def __init__(self, keys, values):
        indx = 0
        for key in keys:
            self.props[key] = values[indx]
            indx += 1
def display(self):
    for key in self.props.keys():
        print 'key=%s value=%s' %(key,self.props[key])

class IntGen:
    def gen(self, keys, values):
        for vs in values:
            yield [keys, vs]

    def start(self, keys, values):
        self.loader = self.gen(keys, values)

    def nextItem(self):
        return self.loader.next()

keys = ['k1', 'k2', 'k3']
values = [['v1.1', 'v1.2', 'v1.3'], ['v2.1', 'v2.2', 'v2.3'], ['v3.1', 'v3.2', 'v3.3']]

holder = []
intGen = IntGen()
intGen.start(keys, values)
while True:
    try:
        a = intGen.nextItem()
        holder.append(deepcopy(IntClass(a[0],a[1])))
    except StopIteration:
        break

for h in holder:
    h.display()

根据我的理解,结果应该是:

key=k3 value=v3.3
key=k2 value=v3.2
key=k1 value=v3.1
key=k3 value=v2.3
key=k2 value=v2.2
key=k1 value=v2.1
key=k3 value=v1.3
key=k2 value=v1.2
key=k1 value=v1.1

但是,我得到如下:

key=k3 value=v3.3
key=k2 value=v3.2
key=k1 value=v3.1
key=k3 value=v3.3
key=k2 value=v3.2
key=k1 value=v3.1
key=k3 value=v3.3
key=k2 value=v3.2
key=k1 value=v3.1

在我看来,在 While 循环中,当我尝试创建 IntClass 的新实例时,该新实例已修改存储在前一个循环中创建的实例的 props 属性中的值,最后导致持有者包含具有相同数据的所有实例。

任何人都可以指出我的答案吗?看起来变量有问题,但我不知道如何修复它。

非常感谢,

4

1 回答 1

2

You put the line props = {} directly in the class definition. This will cause all instances of the class to share the same dictionary.

If you want each instance to have its own dictionary, put self.props = {} in __init__ instead.

于 2012-05-17T10:55:22.433 回答