通过继承自定义功能

Python 面向对象编程入门

George Boorman

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

Ayo berlatih!

Python 面向对象编程入门

Preparing Video For Download...