Python教程

Python - 自定义向量类

本文主要是介绍Python - 自定义向量类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

v0 版本:

# vector2d_v0.py

import math
from array import array


class Vector2d:
    typecode = 'd'  # 转换为字节时的存储方法,d 代表8个字节的双精度浮点数

    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(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)]) +  # 将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))

if __name__ == '__main__':
    v1 = Vector2d(3, 4)
    octets = bytes(v1)
    print(octets)
这篇关于Python - 自定义向量类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!