Python 面向对象编程
Alex Yarosh
Content Quality Analyst @ DataCamp

class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -=amount
# 从 BankAccount 继承的空类
class SavingsAccount(BankAccount):
pass
class SavingsAccount(BankAccount): # SavingsAccount 的专用构造函数,带一个额外参数 def __init__(self, balance, interest_rate):# 用 ClassName.__init__() 调用父类构造函数 BankAccount.__init__(self, balance) # <--- self 是 SavingsAccount 也是 BankAccount# 添加更多功能 self.interest_rate = interest_rate
Parent.__init__(self, args...) 运行父类构造函数# 使用新构造函数创建对象
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
class SavingsAccount(BankAccount):
def __init__(self, balance, interest_rate):
BankAccount.__init__(self, balance)
self.interest_rate = interest_rate
# 新功能
def compute_interest(self, n_periods = 1):
return self.balance * ( (1 + self.interest_rate) ** n_periods - 1)

class CheckingAccount(BankAccount):def __init__(self, balance, limit): BankAccount.__init__(self, balance) self.limit = limitdef deposit(self, amount): self.balance += amountdef withdraw(self, amount, fee=0):if fee <= self.limit: BankAccount.withdraw(self, amount + fee) else: BankAccount.withdraw(self, amount + self.limit)
Parent.method(self, args...) 调用父类方法check_acct = CheckingAccount(1000, 25)
# 将调用 CheckingAccount 的 withdraw
check_acct.withdraw(200)
# 将调用 CheckingAccount 的 withdraw
check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000)
# 将调用 BankAccount 的 withdraw
bank_acct.withdraw(200)
# 将产生错误
bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
keyword argument 'fee'
Python 面向对象编程