在另一个类中调用实例变量

时间:2018-09-23 05:00:48

标签: python class conditional instance-variables

我正在尝试访问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

2 个答案:

答案 0 :(得分:0)

由于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

答案 1 :(得分:0)

class Quote:
    def __init__(self, client=None, lines=[]):
        self.client = client
        self.lines = lines
    def cost(self):
        codes={l.code for l in self.lines}
        price_modifier = 0.9 if codes.issuperset({'door_sign','escape_sign'}) else 1.0
        return sum([l.cost()*price_modifier for l in self.lines])