简体   繁体   中英

python dict() initialisation

Since a few weeks I am learning Python. I have a background in C++, which might explain the question.

It is about the following python code:

#!/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()

The output of this code is:

$ 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

However, I do not understand why the dictionaries in ta1 and ta2 are the same. What is the reason for this behaviour?

The dictionary attribute of TestA belongs to the class and not to its instances. That is the reason why all instances of TestA look the same. You should do this:

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

In class testA the attribute dictionary is an attribute of the class, not of the object (like a static attribute in C++ ). So it is shared by all testA instances. If you want to add the attribute to an object A you have to write something like A.attr , or self.attr somewhere where self is defined that is inside a method. Clearly, unless you have a good reason for not doing so, __init__ is the right place for that.

The answer is plain and simple: That dictionary (there is only one) is created when the class is created. Each instance will share that dict.

If you want one dict to be created for each instance, so it in the __init__() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM