类继承

Python 面向对象编程

Alex Yarosh

Content Quality Analyst @ DataCamp

代码复用

Python 面向对象编程

代码复用

 

1. 已有人实现

 

  • 模块适合固定功能
  • 面向对象适合自定义功能

多个 Python 包的标志

Python 面向对象编程

代码复用

 

1. 已有人实现

 

2. DRY:不要重复自己(Don't Repeat Yourself)

各种 GUI 元素

Python 面向对象编程

代码复用

 

1. 已有人实现

 

2. DRY:不要重复自己(Don't Repeat Yourself)

不要使用各种 GUI 元素

Python 面向对象编程

继承

 

$$\Large{\text{新类功能 = 旧类功能 + 额外功能}}$$

Python 面向对象编程

账户类

Python 面向对象编程

从账户继承的储蓄账户

Python 面向对象编程

两个从账户继承的类

Python 面向对象编程

支票账户中被修改的方法

Python 面向对象编程

实现类继承

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

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

# 继承自 BankAccount 的空类
class SavingsAccount(BankAccount):
    pass

class MyChild(MyParent):
   # Do stuff here
  • MyParent:被扩展/继承功能的类
  • MyChild:继承该功能并添加更多的类
Python 面向对象编程

子类拥有父类的全部数据

# 从 BankAccount 继承的构造函数
savings_acct = SavingsAccount(1000)
type(savings_acct)
__main__.SavingsAccount
# 从 BankAccount 继承的属性
savings_acct.balance
1000
# 从 BankAccount 继承的方法
savings_acct.withdraw(300)
Python 面向对象编程

继承:"是一个"关系

SavingsAccountBankAccount

(可能带有特殊功能)

savings_acct = SavingsAccount(1000)
isinstance(savings_acct, SavingsAccount)
True
isinstance(savings_acct, BankAccount)
True

 

 

acct = BankAccount(500)
isinstance(acct,SavingsAccount)
False
isinstance(acct,BankAccount)
True
Python 面向对象编程

Passons à la pratique !

Python 面向对象编程

Preparing Video For Download...