【问题标题】:Where did I get 0 in the output?我在哪里得到 0 的输出?
【发布时间】:2021-10-30 07:36:08
【问题描述】:

我的目标:重写 process_sale 方法,以便将每笔销售的 2% 添加到奖励中。

我的问题:我是如何在输出中得到 0 的?

练习 5:
使用左侧的父类来帮助您解决这个问题。第一个父类是具有一些非常通用信息的 Person 类。第二个类 CardHolder 是信用卡持有人的类。创建子类 PlantinumClient。这个类继承了两个父类的所有属性。此外,子类具有 cash_back 和奖励属性。 cash_back 应设置为 0.02,rewards 应设置为 0。覆盖 process_sale 方法,以便将每笔销售的 2% 添加到 奖励。

class Person:
  def __init__(self, name, address):
    self.name = name
    self.address = address
    
  def get_info(self):
    return f"{self.name} lives at {self.address}."
  
class CardHolder:
  def __init__(self, account_number):
    self.account_number = account_number
    self.balance = 0
    self.credit_limit = 5000
  
  def process_sale(self, price):
    self.balance += price
    
  def make_payment(self, amount):
    self.balance -= amount
    
# declare child class here
class PlatinumClient(Person, CardHolder):
  def __init__(self, name, address, account_number):
    super().__init__(name, address)
    super(Person, self).__init__(account_number)
    self.cash_back = 0.02
    self.rewards = 0    
  def process_sale(self, price):
      self.rewards += int( (price * 0.02) )

platinum = PlatinumClient("Sarah", "101 Main Street", 123364)  
  
#      Task:                        Expected output:                    
platinum.process_sale(100)      # n/a
print(platinum.rewards)         # 2
print(platinum.balance)         # 100
platinum.make_payment(50)       # n/a
print(platinum.balance)         # 50
print(platinum.get_info())      # Sarah lives at 101 Main Street.

【问题讨论】:

    标签: python oop inheritance


    【解决方案1】:

    您正在覆盖process_sale,但没有调用原始方法。所以没有添加余额。您可以通过运行预期的输出来看到这一点(打印 platinum.balance 产生 0,但应该产生 100)。

    【讨论】:

      猜你喜欢
      • 2011-06-09
      • 2011-05-09
      • 1970-01-01
      • 2014-04-17
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多