Reputation: 1
Background:
I am in the process of creating a script, which creates a production list for a small catering firm. The list should contain three columns (product type, quantity, variant)
Problem:
I have defined a class, which contains information in the order (product type, quantity, variant)
class vareclass:
def __init__(self, vare, qty, meta):
self.vare = vare
self.qty = qty
self.meta = meta
For each product form each order, which is exported from the webshop, I add a class object to a list.
varer.append( vareclass(vare, qty, meta) )
This means, that some products appear multiple times, as more people have ordered them.
How do i count each unique ordered product variant (taking quantity into consideration)?
Upvotes: 0
Views: 118
Reputation: 50819
You can override __eq__
and __hash__
and count the products with dictionary or with collections.Counter
class vareclass:
def __init__(self, vare, qty, meta):
self.vare = vare
self.qty = qty
self.meta = meta
def __eq__(self, other):
return self.vare == other.vare and self.qty == other.qty
def __hash__(self):
return hash(self.vare) + hash(self.qty)
def __repr__(self): # just for the print
return f'{self.vare} {self.qty} {self.meta}'
varer = [vareclass('asd', 3, 'asd'), vareclass('asd', 4, 'asd'), vareclass('asd', 3, 'asd'), vareclass('zxc', 3, 'qwe')]
d = {}
for varec in varer:
d[varec] = d.get(varec, 0) + 1
print(d) # {asd 3 asd: 2, asd 4 asd: 1, zxc 3 qwe: 1}
print(collections.Counter(varer)) # Counter({asd 3 asd: 2, asd 4 asd: 1, zxc 3 qwe: 1})
Upvotes: 3
Reputation: 131
Store them in a set, since sets are a collection of unique objects.
Upvotes: 0