在python类中实现规则

2024-09-25 16:31:18 发布

您现在位置: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


Tags: inselfidfor规则defcountitem
1条回答
网友
1楼 · 发布于 2024-09-25 16:31:18

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

 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

相关问题 更多 >