Lecture 19 Inheritance

1.Attibutes

class Account:
    interest = 0.02
    def __init__(self, account_holder):
        self.holder = account_holder
        self.balance = 0
    def deposit(self, amount):
        self.balance = self.balance + amount
        return self.balance
    def withdraw(self, amount):
        if amount > self.balance:
            return 'Insufficient funds'
        self.balance = self.balance 0 amount
        return self.balance

     

2.attribute assignment

3.Inheritance

Instance attributes are found before class attributes; class attributed are inherited

 inheritance is a method for relating calsses together

    class <name>(<base class>):
        <suite>

the subclass may override certain inherited attributes.

class CheckingAccount(Account):
    withdraw_fee = 1    
    interest = 0.01
    def withdraw(self, amount):   
        return Account.withdraw(self, amount + self.withdraw_fee)
    

Base class attributes aren't copied into subcalsses

if it names an attribute in the class, return the attribute value

otherwise, look up the name in the base class, if there is one.

>>>ch.interest "find trom the CheckAccount"
0.01
>>>ch.deposit(20)"find from the Account"
20
>>>a = Account('John')
>>>b=CheckingAccount('Jack')

4.object_oriented design

don't repeat yuoself;use existing implementations.

class Bank:
   """
   a bank *has* acccounts
   >>>bank = Bank()
   >>>john = bank.open_account('John', 10)
   >>>jack = bank.open_account('Jack', 10)
   >>>john.interest
   0.02
   >>>jack.interest
   0.01
   >>>bank.pay_interest()
   >>>john.balance
   10.2
   """
   def __init__(self):
       self.acconts = []
   def open_account(self, holder, amount, kind=Account):
       account = kind(holder)
       account.deposit(amount)
       self.accounts.append(account)
       return account
   def pay_interest(self):
       for a in self.accounts:
           a.deposit(a.balance * a.interest)
   def too_big_to_fail(self):
       return len(self.accounts) > 1
       

5.attributes lookup practice

6.mutiple inheritance

class SavingsAccount(Account):
    deposit_fee = 2
    def deposit(self, amount):
        return Account.deposit(self, amount - self.deposit_fee)
class AsSeenOnTVAccount(CheckingAccount, SavingAccount):
     def __init__(self, account_holder):
        self.holder = account_holcder
        self.balance = 1
    """
    >>>such = AsSeenOnTVAccount("John")

  7.Complicated Inheritance

rarely use it if you want a clear program

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值