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)