代码之家  ›  专栏  ›  技术社区  ›  Rob

在循环中创建类实例并更新它

  •  1
  • Rob  · 技术社区  · 7 年前

    假设我有一个数据集('test.csv'),如下所示:

    Name,Fruit,Price
    John,Apple,1.00
    Steve,Apple,1.00
    John,Mango,2.00
    Adam,Apple,1.00
    Steve,Banana,1.00
    

    尽管有几种更简单的方法可以做到这一点,但我希望将这些信息组织为python中的一个类。因此,理想情况下,类的实例看起来像:

    {'name': 'John', 'Fruits': ['Apple','Mango'], 'Price':[1.00, 2.00]}
    

    我将数据集加载到类中的方法是将每个实例存储在列表中。

    class org(object):
        def __init__(self,name,fruit,price):
            self.name = name
            self.fruit = [fruit]
            self.price = [price]
    
        classes = []
        with open('test.csv') as f:
            for line in f:
                if not 'Name' in line:
                    linesp=line.rstrip().split(',')
                    name = linesp[0]
                    fruit = linesp[1]
                    price = linesp[2]
                    inst = org(name,fruit,price)
                    classes.append(inst)
        for c in classes:
            print (c.__dict__)
    
    1. 在这种情况下,我如何知道“john”是否已经作为实例存在?

    2. 如果是,如何更新“john”?用ClassMethod?

    @classmethod
        def update(cls, value):
            cls.fruit.append(fruit)
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   shmee    7 年前

    不需要任何特殊的东西来更新你的实例。类的属性是公共的,所以只需访问它们进行更新。

    如果您坚持使用列表作为实例容器,您可以这样做:

    classes = []
    with open('test.csv') as f:
        for line in f:
            if not 'Name' in line:
                name,fruit,price=line.rstrip().split(',')
                exists = [inst for inst in classes if inst.name == name]
                if exists:
                    exists[0].fruit.append(fruit)
                    exists[0].price.append(price)
                else:
                    classes.append(org(name,fruit,price))
    for c in classes:
        print (c.__dict__)
    

    但是,我建议改用dict,因为它使查找和访问实例更加容易

    classes = {}
    with open('test.csv') as f:
        for line in f:
            if not 'Name' in line:
                name,fruit,price=line.rstrip().split(',')
                if name in classes:
                    classes.get(name).fruit.append(fruit)
                    classes.get(name).price.append(price)
                else:
                    classes.update({name: org(name,fruit,price)})
    
    for c in classes.values():
        print (c.__dict__)
    

    两种解决方案都会给您带来相同的结果:

    {'name': 'John', 'fruit': ['Apple', 'Mango'], 'price': ['1.00', '2.00']}
    {'name': 'Steve', 'fruit': ['Apple', 'Banana'], 'price': ['1.00', '1.00']}
    {'name': 'Adam', 'fruit': ['Apple'], 'price': ['1.00']}
    

    为了完整起见,下面注释中的@madfielistic可能意味着更新dict的笨拙方式是,我使用dict的方法,而不是通过订阅访问项。

    # update existing instance in the dict
    classes[name].fruit.append(fruit)
    
    # add new instance to the dict
    classes[name] = org(name, fruit, price)
    

    我个人觉得有点难看,所以我倾向于使用以下方法:)