#!/usr/bin/env python3"""A demonstration of classes and their special methods in Python."""class Vec:"""A simple vector class.Instances of the Vec class can be constructed from numbers>>> a = Vec(1, 2, 3)>>> b = Vec(3, 2, 1)added>>> a + bVec(4, 4, 4)subtracted>>> a - bVec(-2, 0, 2)and multiplied by a scalar on the left>>> 3.0 * aVec(3.0, 6.0, 9.0)or on the right>>> a * 3.0Vec(3.0, 6.0, 9.0)"""def __init__(self, *v):self.v = list(v)@classmethoddef fromlist(cls, v):if not isinstance(v, list):raise TypeErrorinst = cls()inst.v = vreturn instdef __repr__(self):args = ', '.join(repr(x) for x in self.v)return 'Vec({})'.format(args)def __len__(self):return len(self.v)def __getitem__(self, i):return self.v[i]def __add__(self, other):# Element-wise additionv = [x + y for x, y in zip(self.v, other.v)]return Vec.fromlist(v)def __sub__(self, other):# Element-wise subtractionv = [x - y for x, y in zip(self.v, other.v)]return Vec.fromlist(v)def __mul__(self, scalar):# Multiply by scalarv = [x * scalar for x in self.v]return Vec.fromlist(v)__rmul__ = __mul__def test():import doctestdoctest.testmod()test()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。