Python如何设计面向对象的类(下)

开发 后端
经过上下两篇文章的介绍,我们知道了Python风格的类是什么样子的,跟常规的面向对象设计不同的是,Python的类通过魔法方法实现了Python协议,使Python类在使用时能够享受到语法糖,不用通过get和set的方式来编写代码。

[[411673]]

本文将在上篇文章二维向量Vector2d类的基础上,定义表示多维向量的Vector类。

第1版:兼容Vector2d类

代码如下:

  1. from array import array 
  2. import reprlib 
  3. import math 
  4.  
  5.  
  6. class Vector: 
  7.     typecode = 'd' 
  8.  
  9.     def __init__(self, components): 
  10.         self._components = array(self.typecode, components)  # 多维向量存数组中 
  11.  
  12.     def __iter__(self): 
  13.         return iter(self._components)  # 构建迭代器 
  14.  
  15.     def __repr__(self): 
  16.         components = reprlib.repr(self._components)  # 有限长度表示形式 
  17.         components = components[components.find('['):-1] 
  18.         return 'Vector({})'.format(components) 
  19.  
  20.     def __str__(self): 
  21.         return str(tuple(self)) 
  22.  
  23.     def __bytes__(self): 
  24.         return (bytes([ord(self.typecode)]) + 
  25.                 bytes(self._components)) 
  26.  
  27.     def __eq__(self, other): 
  28.         return tuple(self) == tuple(other) 
  29.  
  30.     def __abs__(self): 
  31.         return math.sqrt(sum(x * x for x in self)) 
  32.  
  33.     def __bool__(self): 
  34.         return bool(abs(self)) 
  35.  
  36.     @classmethod 
  37.     def frombytes(cls, octets): 
  38.         typecode = chr(octets[0]) 
  39.         memv = memoryview(octets[1:]).cast(typecode) 
  40.         return cls(memv)  # 因为构造函数入参是数组,所以不用再使用*拆包了 

其中的reprlib.repr()函数用于生成大型结构或递归结构的安全表达形式,比如:

  1. >>> Vector([3.1, 4.2]) 
  2. Vector([3.1, 4.2]) 
  3. >>> Vector((3, 4, 5)) 
  4. Vector([3.0, 4.0, 5.0]) 
  5. >>> Vector(range(10)) 
  6. Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...]) 

超过6个的元素用...来表示。

第2版:支持切片

Python协议是非正式的接口,只在文档中定义,在代码中不定义。比如Python的序列协议只需要__len__和__getitem__两个方法,Python的迭代协议只需要__getitem__一个方法,它们不是正式的接口,只是Python程序员默认的约定。

切片是序列才有的操作,所以Vector类要实现序列协议,也就是__len__和__getitem__两个方法,代码如下:

  1. def __len__(self): 
  2.     return len(self._components) 
  3.  
  4. def __getitem__(self, index): 
  5.     cls = type(self)  # 获取实例所属的类 
  6.     if isinstance(index, slice):  # 如果index是slice切片对象 
  7.         return cls(self._components[index])  # 调用构造方法,返回新的Vector实例 
  8.     elif isinstance(index, numbers.Integral):  # 如果index是整型 
  9.         return self._components[index]  # 直接返回元素 
  10.     else
  11.         msg = '{cls.__name__} indices must be integers' 
  12.         raise TypeError(msg.format(cls=cls)) 

测试一下:

  1. >>> v7 = Vector(range(7)) 
  2. >>> v7[-1]  # <1> 
  3. 6.0 
  4. >>> v7[1:4]  # <2> 
  5. Vector([1.0, 2.0, 3.0]) 
  6. >>> v7[-1:]  # <3> 
  7. Vector([6.0]) 
  8. >>> v7[1,2]  # <4> 
  9. Traceback (most recent call last): 
  10.   ... 
  11. TypeError: Vector indices must be integers 

第3版:动态存取属性

通过实现__getattr__和__setattr__,我们可以对Vector类动态存取属性。这样就能支持v.my_property = 1.1这样的赋值。

如果使用__setitem__方法,那么只能支持v[0] = 1.1。

代码如下:

  1. shortcut_names = 'xyzt'  # 4个分量属性名 
  2.  
  3. def __getattr__(self, name): 
  4.     cls = type(self)  # 获取实例所属的类 
  5.     if len(name) == 1:  # 只有一个字母 
  6.         pos = cls.shortcut_names.find(name
  7.         if 0 <= pos < len(self._components):  # 落在范围内 
  8.             return self._components[pos] 
  9.     msg = '{.__name__!r} object has no attribute {!r}'  # <5> 
  10.     raise AttributeError(msg.format(cls, name)) 
  11.  
  12.  
  13. def __setattr__(self, name, value): 
  14.     cls = type(self) 
  15.     if len(name) == 1:   
  16.         if name in cls.shortcut_names:  # name是xyzt其中一个不能赋值 
  17.             error = 'readonly attribute {attr_name!r}' 
  18.         elif name.islower():  # 小写字母不能赋值,防止与xyzt混淆 
  19.             error = "can't set attributes 'a' to 'z' in {cls_name!r}" 
  20.         else
  21.             error = '' 
  22.         if error: 
  23.             msg = error.format(cls_name=cls.__name__, attr_name=name
  24.             raise AttributeError(msg) 
  25.     super().__setattr__(name, value)  # 其他name可以赋值 

值得说明的是,__getattr__的机制是:对my_obj.x表达式,Python会检查my_obj实例有没有名为x的属性,如果有就直接返回,不调用__getattr__方法;如果没有,到my_obj.__class__中查找,如果还没有,才调用__getattr__方法。

正因如此,name是xyzt其中一个时才不能赋值,否则会出现下面的奇怪现象:

  1. >>> v = Vector([range(5)]) 
  2. >>> v.x = 10 
  3. >>> v.x 
  4. 10 
  5. >>> v 
  6. Vector([0.0, 1.0, 2.0, 3.0, 4.0]) 

对v.x进行了赋值,但实际未生效,因为赋值后Vector新增了一个x属性,值为10,对v.x表达式来说,直接就返回了这个值,不会走我们自定义的__getattr__方法,也就没办法拿到v[0]的值。

第4版:散列

通过实现__hash__方法,加上现有的__eq__方法,Vector实例就变成了可散列的对象。

代码如下:

  1. import functools 
  2. import operator 
  3.  
  4.  
  5. def __eq__(self, other): 
  6.     return (len(self) == len(other) and 
  7.             all(a == b for a, b in zip(self, other))) 
  8.  
  9. def __hash__(self): 
  10.     hashes = (hash(x) for x in self)  # 创建一个生成器表达式 
  11.     return functools.reduce(operator.xor, hashes, 0)  # 计算聚合的散列值 

其中__eq__方法做了下修改,用到了归约函数all(),比tuple(self) == tuple(other)的写法,能减少处理时间和内存。

zip()函数取名自zipper拉链,把两个序列咬合在一起。比如:

  1. >>> list(zip(range(3), 'ABC')) 
  2. [(0, 'A'), (1, 'B'), (2, 'C')] 

第5版:格式化

Vector的格式化跟Vector2d大同小异,都是定义__format__方法,只是计算方式从极坐标换成了球面坐标:

  1. def angle(self, n): 
  2.     r = math.sqrt(sum(x * x for x in self[n:])) 
  3.     a = math.atan2(r, self[n-1]) 
  4.     if (n == len(self) - 1) and (self[-1] < 0): 
  5.         return math.pi * 2 - a 
  6.     else
  7.         return a 
  8.  
  9. def angles(self): 
  10.     return (self.angle(n) for n in range(1, len(self))) 
  11.  
  12. def __format__(self, fmt_spec=''): 
  13.     if fmt_spec.endswith('h'):  # hyperspherical coordinates 
  14.         fmt_spec = fmt_spec[:-1] 
  15.         coords = itertools.chain([abs(self)], 
  16.                                  self.angles()) 
  17.         outer_fmt = '<{}>' 
  18.     else
  19.         coords = self 
  20.         outer_fmt = '({})' 
  21.     components = (format(c, fmt_spec) for c in coords) 
  22.     return outer_fmt.format(', '.join(components)) 

极坐标和球面坐标是啥?我也不知道,略过就好。

小结

经过上下两篇文章的介绍,我们知道了Python风格的类是什么样子的,跟常规的面向对象设计不同的是,Python的类通过魔法方法实现了Python协议,使Python类在使用时能够享受到语法糖,不用通过get和set的方式来编写代码。

 

责任编辑:武晓燕 来源: dongfanger
相关推荐

2021-07-02 14:14:14

Python对象设计

2010-02-02 13:15:26

Python类

2009-01-16 08:52:26

面向对象OOP编程

2023-09-27 23:28:28

Python编程

2012-03-14 10:48:05

C#

2013-04-17 10:46:54

面向对象

2012-06-07 10:11:01

面向对象设计原则Java

2023-11-02 07:55:31

Python对象编程

2010-03-18 13:43:40

python面向对象

2012-12-25 10:51:39

IBMdW

2016-03-11 09:46:26

面向对象设计无状态类

2016-10-11 15:42:08

2013-06-07 11:31:36

面向对象设计模式

2011-07-05 16:05:43

面向对象编程

2010-06-10 10:03:42

UML面向对象

2022-04-01 10:27:04

面向对象串口协议代码

2011-07-05 15:59:57

面向对象编程

2011-07-05 15:22:04

程序设计

2010-07-08 10:47:42

UML面向对象

2010-01-13 14:05:55

C++语言
点赞
收藏

51CTO技术栈公众号