美文网首页
面向对象

面向对象

作者: Rim99 | 来源:发表于2015-12-12 09:59 被阅读25次

    类的定义方法

    class Account:
            def __init__(self, account_holder):
            #必须有`__init__`函数,该函数无需return
                self.balance = 0
                self.holder = account_holder
            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 - amount
                return self.balance
    

    子类的定义

    class CheckingAccount(Account):
            """A bank account that charges for withdrawals."""
            withdraw_charge = 1
            interest = 0.01
            def withdraw(self, amount):
                return Account.withdraw(self, amount + self.withdraw_charge)
    
    
    class SavingsAccount(Account):
            deposit_charge = 2
            def deposit(self, amount):
                return Account.deposit(self, amount - self.deposit_charge) 
    

    多重继承

    python允许多重继承。

    class AsSeenOnTVAccount(CheckingAccount, SavingsAccount):
            def __init__(self, account_holder):
                self.holder = account_holder
                self.balance = 1
    
    多重继承示意图

    相关文章

      网友评论

          本文标题:面向对象

          本文链接:https://www.haomeiwen.com/subject/ucwyhttx.html