在 class python 中实施规则

Implementing rules in a class python

我坚持在 class 中应用规则,例如在存在某些规则时强制更改某些值等等。但是我无法将规则传递给 class。这是我的代码,以及我需要的:

class Item: 
    valid_item_dict = {"a":20, "b":30, "c":40, "d":50}
    def __init__(self, item_id):
        self.item_id = item_id
        self.item_cost = Item.valid_item_dict.get(self.item_id)

class checks:
    def __init__(self):
        self.content = list()
        
    def cheque(self, item):
        self.content.append(item)
        
    def totals(self):
        self.total = sum([self.item_counter().get(itm)*Item.valid_item_dict.get(itm) for\
                          itm in list(self.item_counter().keys())])
        return self.total
    
    def item_counter(self):
        self.item_count_list = [itms.item_id for itms in self.content]
        self.item_count_dict = dict((item, self.item_count_list.count(item)) for item in
                                     self.item_count_list)
        return self.item_count_dict

# Adding items to the list
item1 = Item("a")
item2 = Item("a")
item3 = Item("a")
item4 = Item("b")

# instatiance of class
cx = checks()
cx.cheque(item1)
cx.cheque(item2)
cx.cheque(item3)
cx.cheque(item4)

cx.totals()
>>> 90 (20*3 (from a) + 1*30 (from b))

在正常情况下,这工作正常,但我有大量规则需要添加,我早些时候考虑在“检查”class 的总计方法中添加 if-else 规则。但是他们是添加这些规则的更通用的方法吗?规则类似于如果我们有 3 种类型的产品 a,那么 'a' 的值从 20 减少到 10。 我确实讨论了这个问题并尝试使用它,但任何帮助都会很棒。 ()

您可能希望使用更直接的循环来实现这些规则并使您的代码更清晰。我发现维护复杂的逻辑比尝试编写 1 行结果的高尔夫代码更容易:

 from collections import Counter, namedtuple
 
 Rule = namedtuple("Rule", ["threshold", "newvalue"])
 """rule: if count is greater than or equal to threshold, replace with newvalue"""

 
 class Item:
    rules = {'a': Rule(3, 10)}

    ...

class checks:

    ...

    def totals(self):
        counts = Counter(self.content)
        self.total = 0
        for count in counts:
            value = Item.valid_item_dict[count]
            rule = Item.rules.get(count, Rule(0, value))
            if counts[count] >= rule.threshold:
                value = rule.newvalue
            self.total += value*counts[count]

        return self.total
       

我假设您希望样本的结果为 60 而不是 90。