通过继承自定义功能

Python 面向对象编程

Alex Yarosh

Content Quality Analyst @ DataCamp

账户类的层级结构

Python 面向对象编程

目前已有内容

class BankAccount:
    def __init__(self, balance):
       self.balance = balance

    def withdraw(self, amount):
       self.balance -=amount

# 从 BankAccount 继承的空类
class SavingsAccount(BankAccount):
    pass
Python 面向对象编程

自定义构造函数

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...) 运行父类构造函数
  • 添加更多功能
  • 不必一定调用父类构造函数
Python 面向对象编程

用自定义构造函数创建对象

# 使用新构造函数创建对象
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
Python 面向对象编程

添加功能

  • 照常添加方法
  • 可使用父类和子类的数据
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)

Python 面向对象编程

账户类的层级结构

Python 面向对象编程

自定义功能

class CheckingAccount(BankAccount):

def __init__(self, balance, limit): BankAccount.__init__(self, balance) self.limit = limit
def deposit(self, amount): self.balance += amount
def 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...) 调用父类方法
Python 面向对象编程
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 面向对象编程

Passons à la pratique !

Python 面向对象编程

Preparing Video For Download...