python dict()初始化

2024-05-15 03:33:14 发布

您现在位置:Python中文网/ 问答频道 /正文

从几周前开始,我就在学习Python。我有C++背景,这可能解释这个问题。你知道吗

它是关于以下python代码的:

#!/usr/bin/python2
# -*- coding: utf-8 -*-


class testA:
    dictionary = dict()

    def __init__(self):
        pass


class testB:
    dictionary = None

    def __init__(self):
        self.dictionary = dict()


def main():
    ta1 = testA()
    ta2 = testA()
    tb1 = testB()
    tb2 = testB()

    ta1.dictionary["test1"] = 1
    ta1.dictionary["test2"] = 2
    ta2.dictionary["test3"] = 3
    ta2.dictionary["test4"] = 4

    print "testA ta1"
    for key in ta1.dictionary.keys():
        print "  " + key + "\t" + str(ta1.dictionary[key])
    print "testA ta2"
    for key in ta2.dictionary.keys():
        print "  " + key + "\t" + str(ta2.dictionary[key])


    tb1.dictionary["test1"] = 1
    tb1.dictionary["test2"] = 2
    tb2.dictionary["test3"] = 3
    tb2.dictionary["test4"] = 4

    print "testB tb1"
    for key in tb1.dictionary.keys():
        print "  " + key + "\t" + str(tb1.dictionary[key])
    print "testB tb2"
    for key in tb2.dictionary.keys():
        print "  " + key + "\t" + str(tb2.dictionary[key])

if __name__ == '__main__':
    main()

此代码的输出为:

$ python2 pytest.py 
testA ta1
  test1 1
  test3 3
  test2 2
  test4 4
testA ta2
  test1 1
  test3 3
  test2 2
  test4 4
testB tb1
  test1 1
  test2 2
testB tb2
  test3 3
  test4 4

但是,我不明白为什么ta1和ta2中的词典是一样的。这种行为的原因是什么?你知道吗


Tags: keyinfordictionaryprinttest1test2test3
3条回答

答案很简单:字典(只有一个)是在类创建时创建的。每个实例都将共享该dict

如果您希望为每个实例创建一个dict,那么可以在__init__()方法中使用它。你知道吗

在类testA中,属性dictionary是类的属性,而不是对象的属性(类似于C++中的静态属性)。因此它被所有testA实例共享。如果要将属性添加到对象A,则必须编写类似于A.attrself.attr的内容,其中self是在方法内部定义的。显然,除非你有充分的理由不这么做,__init__才是正确的地方。你知道吗

TestAdictionary属性属于类而不是它的实例。这就是TestA的所有实例看起来相同的原因。您应该这样做:

class TestA:
    def __init__(self):
        self.dictionary = dict() # this will make dictionary belong to the instance, and each instance will get its own copy of dictionary

相关问题 更多 >

    热门问题