附加到python对象字典中的对象列表

时间:2019-12-29 05:34:53

标签: python list class dictionary

我正在创建一个类,该类具有第二个对象的列表以及第二个对象的总金额值。这本身起作用。但是我需要按类别对它们进行分组,因此我创建了它们的字典。但这似乎很简单,但是每当我将对象附加到列表时,它都会附加到字典中的所有列表。

class objA:
    amount = 0
    listBs = []
    category = ""
    def __init__(self,category):
        self.category = category
class objB:
    amount = 0
    category = ""
    otherproperty = ""

mydict = {}

b1 = objB()
b1.amount = 1
b1.category = "foo"
b1.otherproperty = "abc"

if(b1.category not in mydict.keys()):
    mydict[b1.category] = objA(b1.category)
mydict[b1.category].listBs.append(b1)
mydict[b1.category].amount += b1.amount


b2 = objB()
b2.amount = 2
b2.category = "bar"
b2.otherproperty = "xyz"

if(b2.category not in mydict.keys()):
    mydict[b2.category] = objA(b2.category)
mydict[b2.category].listBs.append(b2)
mydict[b2.category].amount += b2.amount

print("foo amount: " + str(mydict["foo"].amount) + " - foo len: " + str(len(mydict["foo"].listBs)))
print("bar amount: " + str(mydict["bar"].amount) + " - bar len: " + str(len(mydict["bar"].listBs)))

当我运行上面的代码时,foo的期望数量为1,bar的期望数量为2,但是两个列表的len均为2,因为它们都包含b1和b2。

我取出了类对象,并且将相同的主要工作附加到列表的字典上,因此以下工作

dictoflists = {}
dictoflists["key1"] = []
dictoflists["key1"].append("k1v1")
dictoflists["key2"] = []
dictoflists["key2"].append("k2v1")
dictoflists["key2"].append("k2v2")
print(dictoflists)

输出:

{'key1': ['k1v1'], 'key2': ['k2v1', 'k2v2']}

是否有办法使它正常工作或提供更好的解决方案?

2 个答案:

答案 0 :(得分:1)

更改objA类的定义,以便在实例之前而不是在类本身上定义变量

class objA:
    def __init__(self, category):
        self.category = category
        self.amount = 0
        self.listBs = []

答案 1 :(得分:1)

所以,我已经在构造函数中初始化了变量-

class objA:
        amount = 0

        category = ""
        def __init__(self,category):
            self.category = category
      #Initialize the variable inside constructor     
            self.listBs = []
class objB:
    amount = 0
    category = ""
    otherproperty = ""

mydict = {}

b1 = objB()
b1.amount = 1
b1.category = "foo"
b1.otherproperty = "abc"

if(b1.category not in mydict.keys()):
    mydict[b1.category] = objA(b1.category)
mydict[b1.category].listBs.append(b1)
mydict[b1.category].amount += b1.amount


b2 = objB()
b2.amount = 2
b2.category = "bar"
b2.otherproperty = "xyz"

if(b2.category not in mydict.keys()):
    mydict[b2.category] = objA(b2.category)
mydict[b2.category].listBs.append(b2)
mydict[b2.category].amount += b2.amount

print("foo amount: " + str(mydict["foo"].amount) + " - foo len: " + str(len(mydict["foo"].listBs)))
print("bar amount: " + str(mydict["bar"].amount) + " - bar len: " + str(len(mydict["bar"].listBs)))