與小卡特一起學python 第14章 物件 動手試一試

yarking207發表於2016-04-07
#14章物件動手試一試
#14.1對應銀行賬戶的類如下所示:
class BankAccout:
    def __init__(self,acct_number,acct_name):
        self.acct_number = acct_number
        self.acct_name = acct_name
        self.balance = 0.0
    def displayBalance(self):
        print("The account balance is:",self.balance)

    def deposit(self,amount):
        self.balance = self.balance + amount
        print("You deposited",amount)
        print("The new balance is:",self.balance)
    def withdraw(self,amount):
        if self.balance >=amount:
            self.balance = self.balance - amount
            print ("You withdrew",amount)
            print ("The new balance is :",self.balance)
        else:
            print("You tried to withdraw",amount)
            print("The account balance is:",self.balance)
            print("Withdrawal denied. Not enough funds.")
myAccount = BankAccout(234567,"Warren Sande")
print("Account name:",myAccount.acct_name)
print("Account number:",myAccount.acct_number)
myAccount.displayBalance()

myAccount.deposit(34.52)
myAccount.withdraw(12.25)
myAccount.withdraw(30.8)

#14.2建立一個賬戶資訊,計算利息
##class InterestAccount(BankAccount):
##    def __init__(self,acct_number,acct_name,rate):
##        BankAccount.__init__(self,acct_number,acct_name)
##        self.rate = rate
##    def addInterest (self):
##        interest = self.balance * self.rate
##        print("adding interest to the account,",self.rate * 100,"percent")
##        self.deposit (interest)

class BankAccount:
    def __init__(self, acct_number, acct_name):
        self.acct_number = acct_number
        self.acct_name = acct_name
        self.balance = 0.0

    def displayBalance(self):
        print( "The account balance is:", self.balance)

    def deposit(self, amount):
        self.balance = self.balance + amount
        print( "You deposited", amount)
        print( "The new balance is:", self.balance)
        
    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance = self.balance - amount
            print( "You withdrew", amount)
            print( "The new balance is:", self.balance)
        else:
            print ("You tried to withdraw", amount)
            print ("The account balance is:", self.balance)
            print("Withdrawl denied.  Not enough funds.")

class InterestAccount(BankAccount):
    def addInterest(self, rate):
        interest = self.balance * rate
        print( "adding interest to the account,",rate * 100,"percent")
        self.deposit (interest)
myAccount = InterestAccount(234567, "Warren Sande")
print ("Account name:", myAccount.acct_name)
print( "Account number:", myAccount.acct_number)
myAccount.displayBalance()
myAccount.deposit(34.52)
myAccount.addInterest(0.11)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/220205/viewspace-2076519/,如需轉載,請註明出處,否則將追究法律責任。

相關文章