【问题标题】:Bank Account Sub classes OOP银行账户子类 OOP
【发布时间】:2021-02-09 07:41:33
【问题描述】:

B)BankAccount 类应该有两个子类,名为 SavingsAccount 和 NonTaxFilerAccount。 SavingsAccount 类应该有一个 ZakatDeduction( ) 函数,该函数在调用时会扣除当前账户余额的 2.5%。  NonTaxFilerAccount 类应该覆盖父类的withdraw 函数。每次提款时都会从账户中扣除 2% 的预扣税。

我做了第一部分,但没有得到第二部分,它一直给我属性错误

class BankAccount:
    def __init__(self, init_bal):
        """Creates an account with the given balance."""
        self.init_bal = init_bal
        self.account = init_bal


    def deposit(self, amount):
        """Deposits the amount into the account."""
        self.amount = amount
        self.account += amount


    def withdraw(self, amount):
       self.account -= amount

    def balance(self):
       print (self.account)
class SavingsAccount(BankAccount) : 
    def ZakatDeduction(self,amount):
       self.account=amount*0.25
       print(self.account)
class NonTaxFilerAccount(BankAccount):
    def withdraw(self, amount):
       self.account -= amount*(0.2)
       print(self.account)
x = BankAccount(700)
x.balance()
y=BankAccount
y.SavingsAccount(700)
z=BankAccount
z.withdraw(70)

【问题讨论】:

    标签: python-3.x oop


    【解决方案1】:

    我认为你有几个问题。基本上,您对 BankAccount、SavingsAccount 和 NonTaxFilerAccount 类的实现在结构上是正确的。然而:

    1. 由于说明说每次调用 ZakatDeduction 时都会将账户余额减少 2.5%,因此您应该更新方法以删除金额,如下所示:
        def ZakatDeduction(self):
            self.account -= self.account*0.025
            print(self.account)  
    
    1. 由于说明说在 NonTaxFiler 进行提款时将账户余额额外减少 2% 的提款金额,因此您应该按如下方式更新 NonTaxFiler 提款方法:
        def withdraw(self, amount):
           self.account -= amount*(1.02)
           print(self.account)
    

    使用这些类创建具有 700 余额的单独帐户应如下所示:

    BA = BankAccount(700)     #Create a base account
    SA = SavingAccount(700)   #Create a Savings Account
    NTF = NonTaxFiler(700)    #Create a NonTaxFilerAccount
    

    执行以下操作会产生:

    BA.withdraw(25)
    BA.balance()
    675  
    
    SA = SavingsAccount(700)
    SA.ZakatDeduction()
    682.5  
    
    NTF = NonTaxFilerAccount(700)
    NTF.withdraw(25)
    674.5
    

    【讨论】:

      【解决方案2】:

      属性错误是正确的,实际上它的消息告诉你问题。你的课没问题。错误在于使用。你有:

      y=BankAccount
      y.SavingsAccount(700)
      

      这意味着y 变量现在引用BankAccount 。下一行尝试调用y.SavingsAccount,而BankAccount 类没有名为SavingsAccount 的方法。

      你是不是想说:

      y = SavingsAccount(700)
      

      请注意,python 是特定于空格的。虽然在技术上有效,但为了可读性,您应该在任何地方使用相同级别的缩进,但是您的一些方法缩进 4,而其他方法缩进 3

      【讨论】:

        猜你喜欢
        • 2011-05-26
        • 1970-01-01
        • 2014-08-27
        • 2015-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 1970-01-01
        相关资源
        最近更新 更多