浅析Python的类、继承和多态

简介:

类的定义

假如要定义一个类 Point,表示二维的坐标点:

 
  1. # point.py 
  2.  
  3. class Point: 
  4.  
  5.     def __init__(self, x=0, y=0): 
  6.  
  7.         self.x, self.y = x, y  

最最基本的就是 __init__ 方法,相当于 C++ / Java 的构造函数。带双下划线 __ 的方法都是特殊方法,除了 __init__ 还有很多,后面会有介绍。

参数 self 相当于 C++ 的 this,表示当前实例,所有方法都有这个参数,但是调用时并不需要指定。

 
  1. >>> from point import * 
  2.  
  3. >>> p = Point(10, 10) # __init__ 被调用 
  4.  
  5. >>> type(p) 
  6.  
  7. <class 'point.Point'
  8.  
  9. >>> p.x, p.y 
  10.  
  11. (10, 10)  

几乎所有的特殊方法(包括 __init__)都是隐式调用的(不直接调用)。

对一切皆对象的 Python 来说,类自己当然也是对象:

 
  1. >>> type(Point) 
  2.  
  3. <class 'type'
  4.  
  5. >>> dir(Point) 
  6.  
  7. ['__class__''__delattr__''__dict__', ..., '__init__', ...] 
  8.  
  9. >>> Point.__class__ 
  10.  
  11. <class 'type'>  

Point 是 type 的一个实例,这和 p 是 Point 的一个实例是一回事。

现添加方法 set:

 
  1. class Point: 
  2.  
  3.     ... 
  4.  
  5.     def set(self, x, y): 
  6.  
  7.         self.x, self.y = x, y  
 
  1. >>> p = Point(10, 10) 
  2.  
  3. >>> p.set(0, 0) 
  4.  
  5. >>> p.x, p.y 
  6.  
  7. (0, 0)  

p.set(...) 其实只是一个语法糖,你也可以写成 Point.set(p, ...),这样就能明显看出 p 就是 self 参数了:

 
  1. >>> Point.set(p, 0, 0) 
  2.  
  3. >>> p.x, p.y 
  4.  
  5. (0, 0)  

值得注意的是,self 并不是关键字,甚至可以用其它名字替代,比如 this:

 
  1. class Point: 
  2.  
  3. ... 
  4.  
  5. def set(this, x, y): 
  6.  
  7. this.x, this.y = x, y  

与 C++ 不同的是,“成员变量”必须要加 self. 前缀,否则就变成类的属性(相当于 C++ 静态成员),而不是对象的属性了。

访问控制

Python 没有 public / protected / private 这样的访问控制,如果你非要表示“私有”,习惯是加双下划线前缀。

 
  1. class Point: 
  2.  
  3.     def __init__(self, x=0, y=0): 
  4.  
  5.         self.__x, self.__y = x, y 
  6.  
  7.   
  8.  
  9.     def set(self, x, y): 
  10.  
  11.         self.__x, self.__y = x, y 
  12.  
  13.   
  14.  
  15.     def __f(self): 
  16.  
  17.         pass  

__x、__y 和 __f 就相当于私有了:

 
  1. >>> p = Point(10, 10) 
  2.  
  3. >>> p.__x 
  4.  
  5. ... 
  6.  
  7. AttributeError: 'Point' object has no attribute '__x' 
  8.  
  9. >>> p.__f() 
  10.  
  11. ... 
  12.  
  13. AttributeError: 'Point' object has no attribute '__f'  

_repr_

尝试打印 Point 实例:

 
  1. >>> p = Point(10, 10) 
  2.  
  3. >>> p 
  4.  
  5. <point.Point object at 0x000000000272AA20>  

通常,这并不是我们想要的输出,我们想要的是:

 
  1. >>> p 
  2.  
  3. Point(10, 10)  

添加特殊方法 __repr__ 即可实现:

 
  1. class Point: 
  2.  
  3. def __repr__(self): 
  4.  
  5. return 'Point({}, {})'.format(self.__x, self.__y)  

不难看出,交互模式在打印 p 时其实是调用了 repr(p):

 
  1. >>> repr(p) 
  2.  
  3. 'Point(10, 10)'  

_str_

如果没有提供 __str__,str() 缺省使用 repr() 的结果。

这两者都是对象的字符串形式的表示,但还是有点差别的。简单来说,repr() 的结果面向的是解释器,通常都是合法的 Python 代码,比如 Point(10, 10);而 str() 的结果面向用户,更简洁,比如 (10, 10)。

按照这个原则,我们为 Point 提供 __str__ 的定义如下:

 
  1. class Point: 
  2.  
  3. def __str__(self): 
  4.  
  5. return '({}, {})'.format(self.__x, self.__y)  

_add_

两个坐标点相加是个很合理的需求。

 
  1. >>> p1 = Point(10, 10) 
  2.  
  3. >>> p2 = Point(10, 10) 
  4.  
  5. >>> p3 = p1 + p2 
  6.  
  7. Traceback (most recent call last): 
  8.  
  9. File "<stdin>", line 1, in <module> 
  10.  
  11. TypeError: unsupported operand type(s) for +: 'Point' and 'Point'  

添加特殊方法 __add__ 即可做到:

 
  1. class Point: 
  2.  
  3. def __add__(self, other): 
  4.  
  5. return Point(self.__x + other.__x, self.__y + other.__y)  
 
  1. >>> p3 = p1 + p2 
  2.  
  3. >>> p3 
  4.  
  5. Point(20, 20)  

这就像 C++ 里的操作符重载一样。

Python 的内建类型,比如字符串、列表,都“重载”了 + 操作符。

特殊方法还有很多,这里就不逐一介绍了。

继承

举一个教科书中最常见的例子。Circle 和 Rectangle 继承自 Shape,不同的图形,面积(area)计算方式不同。

 
  1. # shape.py 
  2.  
  3.   
  4.  
  5. class Shape: 
  6.  
  7.     def area(self): 
  8.  
  9.         return 0.0 
  10.  
  11.          
  12.  
  13. class Circle(Shape): 
  14.  
  15.     def __init__(self, r=0.0): 
  16.  
  17.         self.r = r 
  18.  
  19.   
  20.  
  21.     def area(self): 
  22.  
  23.         return math.pi * self.r * self.r 
  24.  
  25.   
  26.  
  27. class Rectangle(Shape): 
  28.  
  29.     def __init__(self, a, b): 
  30.  
  31.         self.a, self.b = a, b 
  32.  
  33.   
  34.  
  35.     def area(self): 
  36.  
  37.         return self.a * self.b  

用法比较直接:

 
  1. >>> from shape import * 
  2.  
  3. >>> circle = Circle(3.0) 
  4.  
  5. >>> circle.area() 
  6.  
  7. 28.274333882308138 
  8.  
  9. >>> rectangle = Rectangle(2.0, 3.0) 
  10.  
  11. >>> rectangle.area() 
  12.  
  13. 6.0  

如果 Circle 没有定义自己的 area:

 
  1. class Circle(Shape): 
  2.  
  3. pass  

那么它将继承父类 Shape 的 area:

 
  1. >>> Shape.area is Circle.area 
  2.  
  3. True  

一旦 Circle 定义了自己的 area,从 Shape 继承而来的那个 area 就被重写(overwrite)了:

 
  1. >>> from shape import * 
  2.  
  3. >>> Shape.area is Circle.area 
  4.  
  5. False  

通过类的字典更能明显地看清这一点:

 
  1. >>> Shape.__dict__['area'
  2.  
  3. <function Shape.area at 0x0000000001FDB9D8> 
  4.  
  5. >>> Circle.__dict__['area'
  6.  
  7. <function Circle.area at 0x0000000001FDBB70>  

所以,子类重写父类的方法,其实只是把相同的属性名绑定到了不同的函数对象。可见 Python 是没有覆写(override)的概念的。

同理,即使 Shape 没有定义 area 也是可以的,Shape 作为“接口”,并不能得到语法的保证。

甚至可以动态的添加方法:

 
  1. class Circle(Shape): 
  2.  
  3. ... 
  4.  
  5. # def area(self): 
  6.  
  7. return math.pi * self.r * self.r 
  8.  
  9. # 为 Circle 添加 area 方法。 
  10.  
  11. Circle.area = lambda self: math.pi * self.r * self.r  

动态语言一般都是这么灵活,Python 也不例外。

Python 官方教程「9. Classes」第一句就是:

Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics.

Python 以最少的新的语法和语义实现了类机制,这一点确实让人惊叹,但是也让 C++ / Java 程序员感到颇为不适。

多态

如前所述,Python 没有覆写(override)的概念。严格来讲,Python 并不支持「多态」。

为了解决继承结构中接口和实现的问题,或者说为了更好的用 Python 面向接口编程(设计模式所提倡的),我们需要人为的设一些规范。

请考虑 Shape.area() 除了简单的返回 0.0,有没有更好的实现?

以内建模块 asyncio 为例,AbstractEventLoop 原则上是一个接口,类似于 Java 中的接口或 C++ 中的纯虚类,但是 Python 并没有语法去保证这一点,为了尽量体现 AbstractEventLoop 是一个接口,首先在名字上标志它是抽象的(Abstract),然后让每个方法都抛出异常 NotImplementedError。

 
  1. class AbstractEventLoop: 
  2.  
  3. def run_forever(self): 
  4.  
  5. raise NotImplementedError 
  6.  
  7. ...  

纵然如此,你是无法禁止用户实例化 AbstractEventLoop 的:

 
  1. loop = asyncio.AbstractEventLoop() 
  2.  
  3. try: 
  4.  
  5. loop.run_forever() 
  6.  
  7. except NotImplementedError: 
  8.  
  9. pass  

C++ 可以通过纯虚函数或设构造函数为 protected 来避免接口被实例化,Java 就更不用说了,接口就是接口,有完整的语法支持。

你也无法强制子类必须实现“接口”中定义的每一个方法,C++ 的纯虚函数可以强制这一点(Java 更不必说)。

就算子类「自以为」实现了“接口”中的方法,也不能保证方法的名字没有写错,C++ 的 override 关键字可以保证这一点(Java 更不必说)。

静态类型的缺失,让 Python 很难实现 C++ / Java 那样严格的多态检查机制。所以面向接口的编程,对 Python 来说,更多的要依靠程序员的素养。

回到 Shape 的例子,仿照 asyncio,我们把“接口”改成这样:

 
  1. class AbstractShape: 
  2.  
  3. def area(self): 
  4.  
  5. raise NotImplementedError  

这样,它才更像一个接口。

super

有时候,需要在子类中调用父类的方法。

比如图形都有颜色这个属性,所以不妨加一个参数 color 到 __init__:

 
  1. class AbstractShape: 
  2.  
  3. def __init__(self, color): 
  4.  
  5. self.color = color  

那么子类的 __init__() 势必也要跟着改动:

 
  1. class Circle(AbstractShape): 
  2.  
  3. def __init__(self, color, r=0.0): 
  4.  
  5. super().__init__(color) 
  6.  
  7. self.r = r  

通过 super 把 color 传给父类的 __init__()。其实不用 super 也行:

 
  1. class Circle(AbstractShape): 
  2.  
  3. def __init__(self, color, r=0.0): 
  4.  
  5. AbstractShape.__init__(self, color) 
  6.  
  7. self.r = r  

但是 super 是推荐的做法,因为它避免了硬编码,也能处理多继承的情况。


作者:佚名

来源:51CTO

相关文章
|
1月前
|
Python
请简述Python中的继承、封装和多态的概念。
【2月更文挑战第24天】【2月更文挑战第82篇】请简述Python中的继承、封装和多态的概念。
|
7天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
44 0
|
7天前
|
索引 Python
python 格式化、set类型和class类基础知识练习(上)
python 格式化、set类型和class类基础知识练习
23 0
|
8天前
|
Python
python学习12-类对象和实例对象
python学习12-类对象和实例对象
|
29天前
|
Python
Python类(class)中self的理解
Python类(class)中self的理解
17 0
|
29天前
|
Python
Python类定义:从小白到专家的旅程
Python类定义:从小白到专家的旅程
7 0
|
29天前
|
Python
Python继承:深入探索与实际应用
Python中的继承是OOP三大特性之一,允许子类继承父类的属性和方法,实现代码重用和扩展。子类通过`class`关键字和父类名定义,支持单继承和多继承。子类可覆盖父类方法,使用`super()`调用父类同名方法。继承在实际应用中如游戏开发,可创建类体系,提高代码复用性,实现模块化和层次化。掌握继承对于构建高效软件系统至关重要。
|
29天前
|
Python
Python类与对象:深入解析与应用
本文介绍了Python中的核心概念——类和对象,以及它们在面向对象编程中的应用。类是用户定义的类型,描述具有相同属性和行为的对象集合;对象是类的实例,具备类的属性和方法。文章通过示例讲解了如何定义类、创建及使用对象,包括`__init__`方法、属性访问和方法调用。此外,还阐述了类的继承,允许子类继承父类的属性和方法并进行扩展。掌握这些概念有助于提升Python编程的效率和灵活性。
|
1月前
|
机器学习/深度学习 设计模式 开发者
python类用法(四)
python类用法(四)
18 0
|
1月前
|
Python
python类用法(三)
python类用法(三)
16 0