python - 在另一个类中调用实例变量
问题描述
我正在尝试访问 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_sign
都door_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
推荐阅读
- elasticsearch - 弹性搜索:来自 NEST 的 SearchAsync 调用引发关于 ThreadPool 的异常
- php - Laravel,将两个 Eloquent 查询简化为一个
- vba - Word VBA .doc 文件提示用户关闭
- python - Django manage.py runserver 命令在 OSX 上冻结
- python - 如何获取图像的文件?在蟒蛇?django 休息框架
- c - 跨文件传递函数中的 Struct:“预期为 'struct Peer_Information *',但参数类型为 'struct Peer_Information *”
- php - 如何在页面内的 onclick 上重新插入值?
- sql - SQL/VBA 删除两个值之间的行
- mysql - SQL 产生外键约束失败错误
- redis - redis-cli unix socket - 导入 rcmd 失败