在类python中实现规则

问题描述

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

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))

在正常情况下,这可以正常工作,但我需要添加大量规则,而且我之前曾考虑在“checks”类的 totals 方法添加 if-else 规则。但它们是添加这些规则的更通用的方法。规则类似于如果我们有 3 种产品 a,那么“a”的值从 20 减少到 10。 我确实检查了这个问题并试图使用它,但任何帮助都会很棒。 (Python how to to make set of rules for each class in a game)

解决方法

您可能希望使用更直接的循环来实现这些规则并使您的代码更清晰。我发现维护复杂的逻辑比尝试编写 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。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...