创建实例的类dict

时间:2017-11-20 08:04:14

标签: python-3.x class

我想让一个类在字典中跟踪它的实例。例如,对于这门课,我想得到

class Test(object):
    count = 0
    elements = {}
    def __init__(self, a, b):
        self.a = a
        self.b = b
        Test.count += 1

    def __repr__(self):
        return "[a=%s, b=%s]" % (self.a, self.b)

a = Test(1, 3)
b = Test(3, 5)
c = Test(9, 9)
Test.count
# Test.elements # WANT: {1:"a", 2:"b", 3:"c"}

# Added later:
# How to avoid appending to list
Test.el = []                
AA = Test(1, 3)
Test.el.append("AA") # avoid this?
BB = Test(3, 5)
Test.el.append("BB")
CC = Test(9, 9)
Test.el.append("CC")
print(Test.el)
# Then call the AA, BB, CC. Does not work either.
# for o in Test.el:
#     print(o.a)

如何创建像class-count变量一样的元素-dict?

Thx +亲切的问候

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式进行

class Test(object):
    elements = []
    def __init__(self, a, b):
        self.a = a
        self.b = b
        #Test.count += 1
        Test.elements.append(self)

    def __repr__(self):
        return "[a=%s, b=%s]" % (self.a, self.b)

a = Test(1, 3)
b = Test(3, 5)
c = Test(9, 9)
print Test.elements