我有一个类内突然多出的一个属性弄得莫名其妙,我附上了争端代码
整个代码我都能看懂,但是只有一句:
discount = self.promotion.discount(self)
为什么出现这个discount(self)函数, 它是属于哪个类,为什么判定为属于那个类?
```
from abc import ABC,abstractmethod
from collections import namedtuple
Customer = namedtuple('Customer','name fidelity')
#fiedelity是积分的意思,具名元组得到样式为: Custome(name ='', fidelity = '')
class LineItem:
def __init__(self,product,quantity,price):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
#LineItem需要传入 product,quantity,price三个参数,调用它的total()方法会返回每一件的单价*数量的价格
class Order:
def __init__(self,customer,cart,promotion = None):
self.customer = customer
self.cart = cart
self.promotion = promotion
def total(self):
if not hasattr(self,'__total'):
self.__total = sum(item.total() for item in self.cart)
##这一句就是给total()函数赋予 __total的属性
return self.__total
#Order.total() 中的sum(单件商品价格)求和是购物车所以商品的总价格
def due(self):
if self.promotion is None:
discount = 0
# promotion没有传入数值,采用预定的None关键字,因此给出的0折扣赋予了discount = 0
else:
discount = self.promotion.discount(self)
#????????????就是这一句不懂,为什么会有discount()属性
return self.total() - discount
#返回本类中 的 总数 - 折扣数 的打折后的价格
def __repr__(self):
fmt = '<Order类 总价:{:.2f} 打折后: {:.2f}>'
#按样式出结果,而且用的repr魔术方法
return fmt.format(self.total(),self.due())
#这个是显示效果 不用关心
class Promotion(ABC): #抽象基类
@abstractmethod
#声明抽象方法前写这个
def discount(self,order):
#order是需要传入的参数。继承抽象基类的子类在PyCharm里会自动填写出来
"""返回折扣金额"""
class FidelityPromo(Promotion):
def discount(self,order):
return order.total() *.05 if order.customer.fidelity >= 1000 else 0
下面是测试结果:
peter = Customer('PeterPan',10000)
joe = Customer('John',0)
ann = Customer('Ann',1100)
cart = [LineItem('banana',4,3.5),
LineItem('apple',10,5.0),
LineItem('watermellon',1,1.0)]
promo = FidelityPromo()
#FidelityPromo() 实例化了类成为了对象后,不用传入任何参数
tt = Order(peter,cart,promo)
print(tt)
输出:
<Order类 总价:65.00 打折后: 61.75>
得到正常输出了。
```