5.自定义一个实现序列接口的类
自定义的类实现了以下功能:
基本的序列协议——__len__和__getitem__
正确表述拥有很多元素的实例
适当的切片支持,用于生成新的vector实例
综合各个元素的值计算散列值
自定义的格式语言扩展
#实现鸭子模型
from array import array
import math
class Vector2d:
typecode = 'd'
# def __init__(self,x,y):
# self.x = float(x)
# self.y = float(y)
#为了实现类可散列的特性,需要将类变量设成不可变类型也就是加上只读特性(1、设为私有,2、getter方法),最后实现可散列特性
#增加__hash__()
def __init__(self,x,y):
self.__x = float(x)
self.__y = float(y)
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
def __hash__(self):
return hash(self.x) ^ hash(self.y)
def __iter__(self):
return (i for i in (self.x,self.y))
def __repr__(self):
class_name = type(self).__name__
return '{}({!r},{!r})'.format(class_name,*self)
def __str__(self):
return str(tuple(self))
def __bytes__(self):
return (bytes([ord(self.typecode)])+bytes(array(self.typecode,self)))
def __eq__(self,other):
return tuple(self) == tuple(other)
def __abs__(self):
return math.hypot(self.x,self.y)
def __bool__(self):
return bool(abs(self))
#添加备选构造方法
@classmethod
def frombytes(cls,octets):
typecode = chr(octets[0])
memv = memoryview(octets[1:].cast(typecode))
return cls(*memv)
def ang(self):
return math.atan2(self.y,self.x)
#实现format方法
# def __format__(self,fmt_spec=''):
# components = (format(c,fmt_spec)for c in self)
# return '({},{})'.format(*components)
#对format方法拓展极坐标的表示方法
def __format__(self,fmt_spec=''):
if fmt_spec.endswith('p'):
fmt_spec = fmt_spec[:-1]
coords = (abs(self),self.ang())
outer_fmt = '<{},{}>'
else:
coords = self
outer_fmt = '({},{})'
components = (format(c,fmt_spec) for c in coords)
return outer_fmt.format(*components)