Skip to content

第 12 章 面向对象 ​

如果你之前主要写 JavaScript,那么看到 Python 的:

python
class

可能会觉得:

“这个我熟啊,就是面向对象。”

但 Python 的面向对象有一个非常有意思的特点:

它没有要求你必须按照传统 Java / C++ 的方式使用面向对象。

你完全可以写很多 Python 代码而不用自己定义一个 class。

所以学习 Python 的面向对象,最好不要从:

“什么是类?什么是对象?”

这种定义开始。

先看一个问题。


12.1 为什么需要 Class? ​

假设我们要写一个地图程序。

程序里有很多道路:

python
road1_name = "Main Street"
road1_length = 1200
road1_speed_limit = 60

road2_name = "High Street"
road2_length = 800
road2_speed_limit = 40

然后我们还需要操作这些道路:

python
def get_road_info(name, length, speed_limit):
    ...

def calculate_time(length, speed_limit):
    ...

很快你就会发现:

数据和操作开始散落在程序各个地方。

我们真正想表达的是:

text
Road
│
├── name
├── length
├── speed_limit
│
├── info()
└── calculate_time()

也就是说:

把“属于同一个东西的数据”和“操作这些数据的行为”放到一起。

这就是 Class 非常擅长解决的问题。


12.2 Class ​

最简单的 class:

python
class Person:
    pass

现在我们有了一个新的类型:

python
print(Person)

你可以把:

python
Person

理解成一个对象的设计模板。

例如:

text
Person
│
├── name
├── age
│
├── introduce()
└── walk()

然后我们可以根据这个 class 创建对象。


12.3 Object ​

python
class Person:
    pass


person = Person()

这里:

python
Person

是 class。

而:

python
person

是 object。

可以画成:

text
        Class
      ┌────────┐
      │ Person │
      └────┬───┘
           │
       创建对象
           │
           ▼
      ┌──────────┐
      │  person  │
      └──────────┘

所以:

Class 是类型。

Object 是这个类型创建出来的具体对象。

事实上:

python
type(person)

会得到:

python
<class '__main__.Person'>

这和之前学习的:

python
type(10)

非常类似。

text
10        → int 对象
"hello"   → str 对象
[]        → list 对象
person    → Person 对象

12.4 Class 本身也是对象 ​

这里可以把上一章的内容接起来。

你可能会认为:

python
Person

不是对象。

但实际上:

python
type(Person)

会告诉你:

python
<class 'type'>

所以 Python 的对象模型非常有意思:

text
person
   ↓
Person 类型的对象


Person
   ↓
type 类型的对象

也就是说:

class 在 Python 中本身也是对象。

先记住这个事实就够了。

现在不用急着研究 metaclass。


12.5 __init__ ​

现在我们希望每个 Person 都有自己的名字。

可以这样:

python
class Person:
    def __init__(self, name):
        self.name = name

然后:

python
alice = Person("Alice")
bob = Person("Bob")

现在:

python
print(alice.name)

得到:

text
Alice

而:

python
print(bob.name)

得到:

text
Bob

这里最值得注意的是:

python
self.name = name

12.6 self 到底是什么? ​

初学者第一次看到:

python
def __init__(self, name):

通常会问:

self 是 Python 关键字吗?

不是。

self 只是一个约定俗成的参数名。

你甚至可以写:

python
class Person:
    def __init__(this, name):
        this.name = name

语法上也可以工作。

但是不要这么写。

Python 社区约定:

python
self

就是:

当前这个实例对象自己。

所以:

python
alice = Person("Alice")

执行初始化时,可以粗略理解成:

text
self
 ↓
alice

于是:

python
self.name = name

实际上就是:

text
alice.name = "Alice"

12.7 __init__ 到底做什么? ​

很多教程会告诉你:

__init__ 是构造函数。

这个说法虽然方便,但并不完全准确。

更准确地说:

__init__ 是对象创建之后,用来初始化对象的特殊方法。

例如:

python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

然后:

python
person = Person("Alice", 20)

你可以把过程粗略理解成:

text
创建 Person 对象
       ↓
调用 __init__
       ↓
设置 name
       ↓
设置 age
       ↓
得到初始化好的对象

这就是为什么 __init__ 通常用来设置实例的初始状态。


12.8 实例属性 ​

看:

python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

这里:

python
self.name
self.age

就是实例属性。

为什么叫实例属性?

因为每个实例都有自己的一份。

例如:

python
alice = Person("Alice", 20)
bob = Person("Bob", 30)

可以理解成:

text
alice
┌────────────────┐
│ name = Alice   │
│ age = 20       │
└────────────────┘


bob
┌────────────────┐
│ name = Bob     │
│ age = 30       │
└────────────────┘

修改 Alice:

python
alice.age = 21

不会影响 Bob:

python
print(bob.age)

仍然是:

text
30

这就是实例属性的核心特点:

每个实例拥有自己的属性值。


12.9 实例属性甚至可以动态增加 ​

Python 很灵活。

例如:

python
alice = Person("Alice", 20)

alice.city = "New York"

现在:

python
print(alice.city)

可以得到:

text
New York

而:

python
bob.city

会报错。

因为:

text
alice
├── name
├── age
└── city


bob
├── name
└── age

默认情况下,Python 实例通常允许动态添加属性。

这也是 Python 和一些更严格的面向对象语言很不一样的地方。


12.10 实例方法 ​

如果一个对象不只是保存数据,还需要执行行为怎么办?

例如:

python
class Person:
    def __init__(self, name):
        self.name = name

    def introduce(self):
        print(f"Hi, I'm {self.name}.")

然后:

python
alice = Person("Alice")

alice.introduce()

输出:

text
Hi, I'm Alice.

这里:

python
introduce()

就是实例方法。

它的特点是:

方法通常通过实例调用,并且第一个参数接收当前实例。

例如:

python
alice.introduce()

可以粗略理解成:

python
Person.introduce(alice)

所以:

python
self

实际上就是:

text
当前正在调用这个方法的对象

12.11 为什么方法需要 self? ​

来看:

python
class Person:
    def introduce(self):
        print(self.name)

假设:

python
alice = Person("Alice")
bob = Person("Bob")

调用:

python
alice.introduce()

这里:

text
self → alice

调用:

python
bob.introduce()

这里:

text
self → bob

所以同一个方法:

python
introduce()

可以操作不同对象的数据。

这就是实例方法存在的意义。


12.12 类属性 ​

现在我们希望所有 Person 都共享一个信息:

python
species = "Human"

可以写:

python
class Person:
    species = "Human"

    def __init__(self, name):
        self.name = name

然后:

python
alice = Person("Alice")
bob = Person("Bob")

我们可以:

python
print(alice.species)
print(bob.species)

都会得到:

text
Human

这里的:

python
species

是类属性。

它不是每个实例单独创建的属性。

可以理解成:

text
              Person class
                   │
              species="Human"
                   │
          ┌────────┴────────┐
          ▼                 ▼
       alice              bob
      name=Alice         name=Bob

12.13 实例属性和类属性的查找 ​

看:

python
class Person:
    species = "Human"

alice = Person()

执行:

python
alice.species

Python 会先看看:

Alice 自己有没有 species?

如果没有,再去:

Alice 的 class 有没有 species?

所以:

python
alice.species

可以找到:

python
Person.species

但是如果实例自己也有呢? ​

python
alice.species = "Robot"

现在:

python
print(alice.species)

是:

text
Robot

而:

python
print(Person.species)

仍然是:

text
Human

因为现在:

text
alice
├── species = Robot
│
└── 从 Person 继承/查找其他属性


Person
└── species = Human

Alice 自己的属性遮住了类属性。


12.14 类方法 ​

有时候我们需要一个方法:

不关心某一个具体实例,而是操作整个 class。

这时候可以使用:

python
@classmethod

例如:

python
class Person:
    species = "Human"

    @classmethod
    def get_species(cls):
        return cls.species

调用:

python
Person.get_species()

得到:

text
Human

这里:

python
cls

表示:

当前的 class。

就像:

python
self

表示当前实例一样。

可以简单记成:

text
self → instance

cls  → class

12.15 类方法什么时候有用? ​

一个非常经典的用途是:

提供另一种创建对象的方式。

例如:

python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_string(cls, text):
        name, age = text.split(",")
        return cls(name, int(age))

现在:

python
person = Person.from_string("Alice,20")

而不是:

python
person = Person("Alice", 20)

这里:

python
from_string()

就是一个类方法构造器。

这种模式在真实 Python 项目里非常常见。


12.16 为什么这里使用 cls 而不是 Person? ​

注意:

python
return cls(name, int(age))

而不是:

python
return Person(name, int(age))

这是有原因的。

假设以后有人继承:

python
class Employee(Person):
    pass

然后:

python
Employee.from_string("Alice,20")

如果使用:

python
cls(...)

那么创建出来的是:

text
Employee

而不是强行创建:

text
Person

所以:

类方法中的 cls 会让继承体系更加灵活。


12.17 静态方法 ​

还有一种情况:

这个方法和实例没什么关系,也和 class 状态没什么关系。

例如:

python
class MathUtils:

    @staticmethod
    def add(a, b):
        return a + b

调用:

python
MathUtils.add(1, 2)

得到:

text
3

注意:

python
add()

没有:

python
self

也没有:

python
cls

它只是一个放在 class 命名空间里的普通函数。


12.18 三种方法放在一起 ​

现在把三种方法放一起:

python
class Person:

    def introduce(self):
        ...

    @classmethod
    def create(cls):
        ...

    @staticmethod
    def is_valid_name(name):
        ...

可以记成:

text
实例方法
    ↓
self
当前对象


类方法
    ↓
cls
当前 class


静态方法
    ↓
没有 self / cls
只是一个与 class 相关的函数

一个非常实用的判断方法:

如果需要访问实例数据: ​

python
def method(self):

如果需要访问 class: ​

python
@classmethod
def method(cls):

如果两者都不需要: ​

python
@staticmethod
def method(...):

12.19 继承 ​

现在假设我们有:

python
class Person:
    def introduce(self):
        print("Hello")

然后:

python
class Employee(Person):
    pass

这里:

text
Employee
    ↑
    │
继承
    │
Person

所以:

python
employee = Employee()

employee.introduce()

可以正常调用。

虽然我们没有在 Employee 里面写:

python
introduce()

因为它继承了 Person 的方法。


12.20 为什么需要继承? ​

继承解决的是:

“这个类型和另一个类型有什么共同点?”

例如:

text
Person
│
├── name
├── age
└── introduce()
      ↑
      │
   Employee
      │
      └── salary

Employee 是一种 Person。

所以可以共享:

python
name
age
introduce()

然后增加:

python
salary

12.21 super() ​

如果子类需要扩展父类的初始化:

python
class Person:
    def __init__(self, name):
        self.name = name


class Employee(Person):
    def __init__(self, name, salary):
        super().__init__(name)
        self.salary = salary

现在:

python
employee = Employee("Alice", 10000)

这个对象拥有:

text
name
salary

其中:

python
super().__init__(name)

负责调用父类的初始化逻辑。

可以理解成:

“先把父类该做的事情做完,再做子类自己的事情。”


12.22 多态 ​

多态这个词听起来很吓人。

其实先看代码。

python
class Dog:
    def speak(self):
        print("Woof")


class Cat:
    def speak(self):
        print("Meow")

现在:

python
def make_sound(animal):
    animal.speak()

可以:

python
make_sound(Dog())
make_sound(Cat())

结果:

text
Woof
Meow

注意:

python
make_sound()

根本不需要知道:

你到底是 Dog 还是 Cat。

它只需要:

text
你有没有 speak()?

这就是多态非常核心的思想:

同一个操作,不同对象可以表现出不同的行为。


12.23 Python 的多态和 Java 有什么不同? ​

Python 不要求你必须声明:

text
Dog implements Animal
Cat implements Animal

也不一定要求:

text
Dog extends Animal
Cat extends Animal

Python 更在乎:

python
animal.speak()

这个东西能不能运行。

如果:

python
animal

有:

python
speak()

那么就可以。

这就引出了 Python 一个非常重要的概念:

鸭子类型(Duck Typing)


12.24 鸭子类型 ​

鸭子类型来自一句经典的描述:

如果它走起来像鸭子,叫起来像鸭子,那么它就可以当鸭子用。

Python 不太关心:

“你到底属于哪个 class?”

而更加关心:

“你有没有我需要的行为?”

例如:

python
class Dog:
    def speak(self):
        print("Woof")


class Robot:
    def speak(self):
        print("Beep")

然后:

python
def speak_twice(obj):
    obj.speak()
    obj.speak()

现在:

python
speak_twice(Dog())

输出:

text
Woof
Woof

而:

python
speak_twice(Robot())

输出:

text
Beep
Beep

函数完全不需要知道:

text
Dog?
Robot?
Person?

它只关心:

text
有没有 speak()?

12.25 鸭子类型比继承更重要 ​

这是 Python 面向对象中非常值得建立的一个观念。

传统面向对象容易让人想到:

text
Animal
  ↑
  ├── Dog
  ├── Cat
  └── Bird

然后:

python
def make_sound(animal):
    ...

只能接收:

text
Animal

Python 更喜欢:

text
任何对象
   │
   ├── speak() → 可以
   │
   └── speak() → 不可以

例如:

python
class Dog:
    def speak(self):
        print("Woof")


class Human:
    def speak(self):
        print("Hello")


class Robot:
    def speak(self):
        print("Beep")

它们甚至没有继承同一个父类。

但是:

python
def speak(obj):
    obj.speak()

依然可以处理它们。

这就是 Python 风格的多态。


12.26 封装 ​

“封装”这个词也很容易被教材讲得特别复杂。

先从一个简单目标开始:

不要让调用者随便破坏对象的内部状态。

例如:

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

外部可以:

python
account.balance = -100000

显然不太理想。

我们可能希望:

余额不能随便被修改。

Python 没有 Java 那种严格意义上的:

text
private
protected
public

但 Python 提供了一套约定和机制。


12.27 单下划线 ​

例如:

python
class BankAccount:
    def __init__(self):
        self._balance = 0

这里:

python
_balance

表示:

这是内部使用的属性,请不要从外部随便操作。

但注意:

Python 不会真的禁止你:

python
account._balance = 100

它主要是一种约定。

也就是说:

text
_balance
   ↓
“这是内部实现”

而不是:

text
“绝对不能访问”

12.28 双下划线 ​

再看:

python
class Person:
    def __init__(self):
        self.__name = "Alice"

这会触发 Python 的 name mangling(名称改写)。

例如:

python
person.__name

通常不能直接访问。

Python 会把它改写成类似:

text
_Person__name

所以:

python
person._Person__name

理论上仍然可以访问。

这说明一个非常重要的事实:

Python 的封装更强调“约定”和“避免意外访问”,而不是绝对禁止。


12.29 属性访问和 property ​

Python 还有一种非常漂亮的封装方式:

python
class Person:
    def __init__(self, age):
        self._age = age

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if value < 0:
            raise ValueError("age cannot be negative")

        self._age = value

现在:

python
person = Person(20)

可以:

python
print(person.age)

也可以:

python
person.age = 30

但:

python
person.age = -10

会触发:

text
ValueError

这里的好处是:

调用者看到的仍然是:

python
person.age

而不是:

python
person.get_age()
person.set_age()

这非常符合 Python 的风格:

让接口简单,把实现细节隐藏起来。


12.30 一个完整的类 ​

现在把刚才学到的东西组合起来。

python
class Person:
    species = "Human"

    def __init__(self, name, age):
        self.name = name
        self._age = age

    def introduce(self):
        return f"I'm {self.name}."

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if value < 0:
            raise ValueError("age cannot be negative")

        self._age = value

    @classmethod
    def create_adult(cls, name):
        return cls(name, 18)

    @staticmethod
    def is_valid_name(name):
        return bool(name.strip())

现在这个 class 同时包含:

text
Person
│
├── 类属性
│   └── species
│
├── 初始化
│   └── __init__
│
├── 实例属性
│   ├── name
│   └── _age
│
├── 实例方法
│   └── introduce()
│
├── property
│   └── age
│
├── 类方法
│   └── create_adult()
│
└── 静态方法
    └── is_valid_name()

12.31 什么时候应该使用 Class? ​

这里有一个比“面向对象定义”更实用的问题:

什么时候值得写 class?

一个不错的判断方式是:

如果你的程序中存在一个东西,它同时具有:

text
状态 + 行为

那么 class 往往就很自然。

例如:

text
User
    状态:name、email
    行为:login()、logout()


Order
    状态:items、total
    行为:add_item()、pay()


Map
    状态:center、zoom
    行为:pan()、zoom_in()


Road
    状态:geometry、speed_limit
    行为:length()、calculate_time()

这时候把它们组织成对象通常很合理。


12.32 但不要为了面向对象而面向对象 ​

Python 并不要求:

text
一个函数
→ 一个 class


一个数据结构
→ 一个 class

例如:

python
def add(a, b):
    return a + b

没有必要因为“面向对象”而写成:

python
class Calculator:
    def add(self, a, b):
        return a + b

这反而可能让代码变复杂。

Python 更强调:

使用最简单的抽象解决问题。

有时候:

python
dict + function

就足够了。

有时候:

python
class

才是更好的表达。


12.33 Class、Object、实例属性、类属性 ​

最后把几个容易混淆的概念放在一起。

python
class Person:
    species = "Human"

    def __init__(self, name):
        self.name = name

然后:

python
alice = Person("Alice")
bob = Person("Bob")

现在:

text
Person
│
├── species = "Human"       ← 类属性
│
└── __init__()


alice
│
└── name = "Alice"          ← 实例属性


bob
│
└── name = "Bob"            ← 实例属性

所以:

text
Class
    ↓
定义一类对象


Object / Instance
    ↓
具体的一个对象


Instance attribute
    ↓
某一个对象自己的数据


Class attribute
    ↓
属于 class 的数据

12.34 四种方法放在一起 ​

再看:

python
class Example:

    def instance_method(self):
        pass

    @classmethod
    def class_method(cls):
        pass

    @staticmethod
    def static_method():
        pass

可以建立一个非常简单的判断模型:

text
instance_method
      │
      └── 需要“我这个对象”的数据
              ↓
             self


class_method
      │
      └── 需要“这个类”的数据
              ↓
             cls


static_method
      │
      └── 两者都不需要
              ↓
          普通函数

12.35 继承 vs 鸭子类型 ​

这是 Python 面向对象最值得比较的一组概念。

继承 ​

关注:

你是什么?

例如:

text
Dog
  ↓
Animal

Dog 是 Animal。


鸭子类型 ​

关注:

你能做什么?

例如:

text
Dog       → speak()
Robot     → speak()
Human     → speak()

它们不一定有共同父类。

但都可以:

python
obj.speak()

所以 Python 代码经常更偏向:

text
“我需要什么行为?”

而不是:

text
“你属于哪个继承体系?”

这也是 Python 面向对象和传统 Java/C++ 面向对象思维非常不同的地方。


12.36 本章真正需要记住的东西 ​

如果你只记住下面这些,就足够了。

① Class 是一种类型 ​

python
class Person:
    pass

② Object 是 class 创建出来的具体实例 ​

python
person = Person()

③ __init__ 用来初始化实例 ​

python
def __init__(self, name):
    self.name = name

④ self 表示当前实例 ​

python
person.introduce()

可以粗略理解成:

python
Person.introduce(person)

⑤ 实例属性属于具体对象 ​

python
self.name

Alice 和 Bob 可以有不同的 name。


⑥ 类属性属于 class ​

python
class Person:
    species = "Human"

多个实例可以共享它。


⑦ 类方法使用 cls ​

python
@classmethod
def create(cls):
    ...

它操作的是 class。


⑧ 静态方法不需要 self 或 cls ​

python
@staticmethod
def add(a, b):
    return a + b

它本质上就是一个放在 class 命名空间中的函数。


⑨ 继承让子类复用父类行为 ​

python
class Employee(Person):
    pass

⑩ 多态意味着同一个操作可以产生不同的行为 ​

python
obj.speak()

Dog、Cat 可以有不同实现。


⑪ Python 的封装更多依赖约定 ​

text
name       → 普通公开属性
_name      → 内部使用的约定
__name     → 名称改写
@property  → 控制属性访问

⑫ Python 非常重视鸭子类型 ​

最重要的不是:

text
“你是什么类型?”

而是:

text
“你有没有我需要的行为?”

12.37 最后一个练习:先预测,再运行 ​

最后做一个综合练习。

不要直接运行。

先想一想:

python
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError


class Dog(Animal):
    def speak(self):
        return f"{self.name}: Woof!"


class Cat(Animal):
    def speak(self):
        return f"{self.name}: Meow!"


class Robot:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name}: Beep!"


def make_sound(obj):
    print(obj.speak())


animals = [
    Dog("Buddy"),
    Cat("Mimi"),
    Robot("R2D2"),
]

for animal in animals:
    make_sound(animal)

你应该先回答:

  1. Animal 是什么?
  2. Dog("Buddy") 是什么?
  3. self.name 是实例属性还是类属性?
  4. speak() 是实例方法还是类方法?
  5. Dog 和 Cat 为什么可以传给 make_sound()?
  6. Robot 没有继承 Animal,为什么仍然可以传进去?
  7. 这里体现了什么?
  8. 如果 Robot 没有 speak(),会发生什么?

最后你会发现:

text
Class
  ↓
创建 Object
  ↓
Object 拥有自己的状态
  ↓
Object 拥有自己的行为
  ↓
继承可以复用行为
  ↓
多态允许不同对象提供相同接口
  ↓
鸭子类型让 Python 不强制要求继承关系

而这其实就是 Python 面向对象最核心的一条线:

把数据和行为组织成对象;需要复用时使用继承;需要统一使用方式时依靠多态;而在 Python 里,很多时候甚至不需要关心对象到底属于哪个类,只要它提供我们需要的行为即可。

这比死记:

text
Class
Object
Inheritance
Polymorphism
Encapsulation

重要得多。

因为当你真正开始写 Python 项目时,你最终面对的问题永远不是:

“请告诉我多态的定义。”

而是:

“这段代码里的数据和行为,应该怎么组织,才能让以后修改起来更容易?”

这才是面向对象真正要解决的问题。