Python 面向对象编程入门
George Boorman
Curriculum Manager, 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__() 调用父类构造函数 # self 是 SavingsAccount,也是 BankAccount BankAccount.__init__(self, balance)# 添加更多功能 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): # 新增 fee 参数if amount <= self.limit: BankAccount.withdraw(self, amount + fee) else: pass # 条件不满足则不执行
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 面向对象编程入门