python学习笔记五——自定义一个实现序列接口的类

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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值