gpt4 book ai didi

python - 调用另一个类中的实例变量

转载 作者:太空宇宙 更新时间:2023-11-03 21:46:20 25 4
gpt4 key购买 nike

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

最佳答案

看起来您总是在提供折扣,因为 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

关于python - 调用另一个类中的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52463142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com