首页 > 解决方案 > 在另一个类中调用实例变量

问题描述

我正在尝试访问 Quote 类中 Line 类中的实例变量 self.code。我正在尝试使以下规则通过:当报价同时包含“door_sign”和“escape_sign”行时,他们将获得整个报价 10% 的折扣。

这是代码。

class Client:
    def __init__(self, postcode):
        self.postcode = postcode


class Line:
    def __init__(self, code, unit_cost, quantity=1):
        self.code = code
        self.unit_cost = unit_cost
        self.quantity = quantity

    def cost(self):

        if self.code == 'door_sign' and self.quantity >=3:
            return self.unit_cost * self.quantity * 0.8
        else:
            return self.unit_cost * self.quantity

class Quote:
    def __init__(self, client=None, lines=[]):
        self.client = client
        self.lines = lines

    def cost(self):

****这是我的问题所在****

    for l in self.lines:
        if line.code == 'door_sign' and 'escape_sign':
            return sum([l.cost() * 0.9])
        else:
            return sum([l.cost()])

print('Rule')
assert Quote(client=Client(postcode=3000), lines=[
Line(code='escape_sign', unit_cost=20.0, quantity=10),
]).cost() == 200.0
assert Quote(client=Client(postcode=3000), lines=[
Line(code='door_sign', unit_cost=10.0, quantity=1),
Line(code='escape_sign', unit_cost=20.0, quantity=10),
]).cost() == 189.0

标签: pythonclassconditionalinstance-variables

解决方案


看起来你总是给折扣,因为escape_sign总是True和通过提前返回错误地计算成本。你为什么不在def cost方法中试试这个:

def cost(self):
    needed = {'door_sign', 'escape_sign'}
    discount = {l.code for l in self.lines} & needed == needed
    cost = sum(l.cost() for l in self.lines)
    return (cost * 0.9) if discount else cost

快速编辑,我错过了你想要折扣,如果两者 escape_signdoor_sign在订单中。

如果你想在一个循环中:

def cost(self):
    door = False
    escape = False
    cost = 0
    for line in self.lines:
        if line.code == 'escape_sign':
            escape = True
        elif line.code == 'door_sign':
            door = True
        cost += line.cost()
    return (cost * 0.9) if (escape and door) else cost

推荐阅读