dictionary - python dict() initialisation -
since few weeks learning python. have background in c++, might explain question.
it 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" key in ta1.dictionary.keys(): print " " + key + "\t" + str(ta1.dictionary[key]) print "testa ta2" 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" key in tb1.dictionary.keys(): print " " + key + "\t" + str(tb1.dictionary[key]) print "testb tb2" key in tb2.dictionary.keys(): print " " + key + "\t" + str(tb2.dictionary[key]) if __name__ == '__main__': main()
the output of 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, not understand why dictionaries in ta1 , ta2 same. reason behaviour?
the dictionary
attribute of testa
belongs class , not instances. reason why instances of testa
same. should this:
class testa: def __init__(self): self.dictionary = dict() # make dictionary belong instance, , each instance own copy of dictionary
Comments
Post a Comment