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