从几周前开始,我就在学习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中的词典是一样的。这种行为的原因是什么?你知道吗
答案很简单:字典(只有一个)是在类创建时创建的。每个实例都将共享该dict
如果您希望为每个实例创建一个dict,那么可以在
__init__()
方法中使用它。你知道吗在类
testA
中,属性dictionary
是类的属性,而不是对象的属性(类似于C++
中的静态属性)。因此它被所有testA
实例共享。如果要将属性添加到对象A
,则必须编写类似于A.attr
或self.attr
的内容,其中self
是在方法内部定义的。显然,除非你有充分的理由不这么做,__init__
才是正确的地方。你知道吗TestA
的dictionary
属性属于类而不是它的实例。这就是TestA
的所有实例看起来相同的原因。您应该这样做:相关问题 更多 >
编程相关推荐