【python进阶】模拟数值类型

from math import hypot
class Vector:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __repr__(self):   #定义输出表示方法
        return 'Vector(%r, %r)' % (self.x, self.y)

    def __abs__(self):
        return hypot(self.x, self.y)    #求向量的模

    def __bool__(self):
        return bool(abs(self))

    def __add__(self, other):   #定义+方法
        x = self.x + other.x
        y = self.y + other.y
        return Vector(x, y)

    def __mul__(self, other):   #定义 * 方法
        return Vector(self.x * other, self.y * other)

v1 = Vector(2,4)
v2 = Vector(2,1)
print(v1 + v2)
v = Vector(3, 4)
print(abs(v))
print(abs(v * 3))

【python进阶】模拟数值类型

相关文章:

  • 2021-07-19
  • 2021-09-22
  • 2021-08-23
  • 2021-08-31
  • 2021-05-30
  • 2021-12-02
  • 2022-12-23
  • 2021-05-28
猜你喜欢
  • 2021-12-09
  • 2022-02-16
  • 2022-01-17
  • 2021-07-05
  • 2022-12-23
  • 2021-08-09
相关资源
相似解决方案