本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,,版权归原作者所有,如有问题请及时联系我们以作处理
作者:测试游记 来源:推酷
想要获取更多Python学习资料,了解更多关于Python的知识,可以加Q群630390733踊跃发言,大家一起来学习讨论吧!
把协议当作正式接口
repr
reprlib.repr
用于生成大型结构或递归结构的安全表示形式。
它会限制输出字符串的长度,用「…」表示截断的部分。
注意:调用 __repr__
函数的目的是调试,因此绝对不能抛出异常,尽量输出有用的内容,让用户能够识别目标对象。
协议
在面向对象编程中,协议是非正式的接口,只在文档中定义,在代码中不定义。
协议是非正式的,没有强制力,因此如果知道类的具体使用场景,通常只需要实现一个协议的部分。
切片原理
class A: def __getitem__(self, item): return item if __name__ == '__main__': a = A() print(a[1]) # 1 print(a[1:4]) # slice(1, 4, None) print(a[1:4:2]) # slice(1, 4, 2) print(a[1:4:2, 9]) # (slice(1, 4, 2), 9) print(a[1:4:2, 7:9]) # (slice(1, 4, 2), slice(7, 9, None))
slice是内置的类型,它的indices方法开放了内置序列实现的逻辑,用于优雅的处理缺失索引和负数索引,以及长度超过目标序列的切片。
class slice
( start , stop [, step ])
返回一个表示由 range(start, stop, step)
所指定索引集的 slice 对象。其中 start 和 step 参数默认为 None
。切片对象具有仅会返回对应参数值(或其默认值)的只读数据属性 start
, stop
和 step
。它们没有其他的显式功能;不过它们会被 NumPy 以及其他第三方扩展所使用。切片对象也会在使用扩展索引语法时被生成。例如: a[start:stop:step]
或 a[start:stop, i]
。
# [:10:2] [0:5:2] slice(None, 10, 2).indices(5) # (0, 5, 2) # [-3::] [2:5:1] slice(-3, None, None).indices(5) # (2, 5, 1)
indices
获取实例所属类
通过 type(self)
可以拿到实例所属的类
动态存取属性
属性查找失败后,解释器会调用 __getattr__
方法。
示例代码
# -*- coding: utf-8 -*- # @Time : 2020/12/27 下午3:07 # @Author : zhongxin # @Email : 490336534@qq.com # @File : vector.py import itertools import numbers import functools import operator from array import array import reprlib import math class Vector: typecode = 'd' # 类属性 shortcut_names = 'xyzt' def __init__(self, components): self._components = array(self.typecode, components) def __iter__(self): return iter(self._components) def __repr__(self): components = reprlib.repr(self._components) components = components[components.find('['):-1] return f'Vector({components})' def __str__(self): return str(tuple(self)) def __bytes__(self): return (bytes([ord(self.typecode)]) + bytes(self._components)) def __eq__(self, other): # if len(self) != len(other): # return False # for a, b in zip(self, other): # if a != b: # return False # return True return len(self) == len(other) and all(a == b for a, b in zip(self, other)) def __hash__(self): # hashes = (hash(x) for x in self._components) hashes = map(hash, self._components) return functools.reduce(operator.xor, hashes, 0) def __abs__(self): return math.sqrt(sum(x * x for x in self)) def __bool__(self): return bool(abs(self)) def __len__(self): return len(self._components) def __getitem__(self, item): cls = type(self) # 获取实例所属类 if isinstance(item, slice): return cls(self._components[item]) elif isinstance(item, numbers.Integral): return self._components[item] else: msg = '{cls.__name__} 切片必须是整数' raise TypeError(msg.format(cls=cls)) def __getattr__(self, name): cls = type(self) if len(name) == 1: pos = cls.shortcut_names.find(name) if 0 <= pos < len(self._components): return self._components[pos] msg = '{.__name__!r} object has no attribute {!r}' raise AttributeError(msg.format(cls, name)) def __setattr__(self, name, value): cls = type(self) if len(name) == 1: if name in cls.shortcut_names: error = 'readonly attribute {attr_name!r}' elif name.islower(): error = "can't set attributes 'a' to 'z' in {cls_name!r}" else: error = '' if error: msg = error.format(cls_name=cls.__name__, attr_name=name) raise AttributeError(msg) super().__setattr__(name, value) def angle(self, n): r = math.sqrt(sum(x * x for x in self[n:])) a = math.atan2(r, self[n - 1]) if (n == len(self) - 1) and (self[-1] < 0): return math.pi * 2 - a else: return a def angles(self): return (self.angle(n) for n in range(1, len(self))) def __format__(self, format_spec=''): if format_spec.endswith('h'): format_spec = format_spec[:-1] coords = itertools.chain([abs(self)], self.angles()) outer_fmt = '<{}>' else: coords = self outer_fmt = '({})' components = (format(c, format_spec) for c in coords) return outer_fmt.format(','.join(components)) @classmethod def frombytes(cls, octets): typecode = chr(octets[0]) memv = memoryview(octets[1:]).cast(typecode) return cls(memv)