自定义序列的修改、散列和切片

# -*- coding: utf-8 -*-
# ------------------------------------序列的修改、散列和切片------------------------------------
from array import array
import reprlib
import math
import numbers
import itertools
import functools
import operator


class Vector:
    type_code = 'd'
    shortcut_names = "xyzt"

    def __init__(self, components):
        self._components = array(self.type_code, components)

    def __iter__(self):
        return iter(self._components)

    def __repr__(self):
        components = reprlib.repr(self._components)
        components = components[components.find('['):-1]
        return 'Vector({})'.format(components)

    def __str__(self):
        return str(tuple(self))

    def __bytes__(self):
        return bytes([ord(self.type_code)]) + bytes(self._components)

    def __hash__(self):
        """
        使用reduce函数时最好提供第三个参数initial。如果序列为空,initial是返回的结果。
        当序列不为空时,在归约中使用initial作为第一个参数,因此应该使用恒等值。
        比如,对+ 、|和^来说,initial应该是0;而对*和&来说,应该是1。
        """
        hashes = map(hash, self._components)  # 映射
        return functools.reduce(operator.xor, hashes, 0)  # 归约
        # return functools.reduce(lambda a,b:a^b, hashes, 0)

    def __eq__(self, other):
        """
        为了提高比较的效率,Vector.__eq__方法在for循环中使用zip函数
        拓展:for循环经常会与zip、enumerate(为了避免手动处理索引)等生成器函数并用。
        """
        # if len(self) != len(other):
        #     # 如果两个对象的长度不一样,那么它们不相等
        #     return False
        # for a, b in zip(self, other):
        #     # zip函数生成一个由元组构成的生成器,元组中的元素来自参数传入的各个可迭代对象。
        #     # 前面比较长度的测试是有必要的。因为一旦有一个输入耗尽,zip函数会立即停止生成值,并且不发出警告。
        #     # 这个的效率已经比较好了,不过用于计算聚合值的整个for循环可以替换成一行all函数调用。
        #     if a != b:
        #         # 只要有两个分量不同,返回False
        #         return False
        # return True
        return len(self) == len(other) and all(a == b for a, b in zip(self, other))

    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, index):
        cls = type(self)  # 获取实例所属的类,供后面使用
        if isinstance(index, slice):
            # 如果传入的index参数是slice对象,则使用_components数组的切片结果构建一个新的Vector
            return cls(self._components[index])
        elif isinstance(index, numbers.Integral):
            # 如果传入的index参数是int或其它整数类型,那么就返回_components中相应的元素
            return self._components[index]
        else:
            # 否则抛出异常
            msg = "{cls.__name__} indices must be integers"
            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):
                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 self.shortcut_names:
                error = 'readonly attribute {attr_name!r}'
            elif name.islower():
                error = "can't set attribute 'a' to 'z' in {cls_name!}"
            else:
                error = ''
            if error:
                msg = error.format(cls_name=cls.__name__, attr_name=name)
                raise AttributeError(msg)

        super(Vector, self).__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: str):
        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, bytes_):
        type_code = chr(bytes_[0])
        memv = memoryview(bytes_[1:]).cast(type_code)
        return cls(memv)
posted @ 2020-08-11 17:17  怀心抱素  阅读(115)  评论(0编辑  收藏  举报