Python类:使用uu Add向向量中的每个元素添加一个数字__
假设我有一个向量(a_1,a_2,a_3,…,a_n) 我想使用python类中的uu add uu向向量的每个元素添加一个数字 以便: a=向量(7,4,2) 打印a+3 将输出:(10、7、5) 请帮忙。对于这个问题,我的代码是什么Python类:使用uu Add向向量中的每个元素添加一个数字__,python,class,add,Python,Class,Add,假设我有一个向量(a_1,a_2,a_3,…,a_n) 我想使用python类中的uu add uu向向量的每个元素添加一个数字 以便: a=向量(7,4,2) 打印a+3 将输出:(10、7、5) 请帮忙。对于这个问题,我的代码是什么 非常感谢。这里有一个简单的实现: class Vector(): def __init__(self, *args): self.args = args def __add__(self, other): re
非常感谢。这里有一个简单的实现:
class Vector():
def __init__(self, *args):
self.args = args
def __add__(self, other):
return tuple(map(lambda x:x+other,self.args))
a = Vector(1,2,3,4,5)
print a+3
class vector(object):
def __init__(self, *args):
self.args = args
def __add__(self, other):
if not isinstance(other, int):
raise TypeError("Cannot add {} with {}".format(type(self), type(other)))
return vector(*(arg + other for arg in self.args))
def __repr__(self):
return "vector({})".format(", ".join(map(str, self.args)))
a = vector(7, 4, 2)
print a + 3 # (10, 7, 5)
输出:
vector(10, 7, 5)
我假设你的
(10,7,4)
应该是(10,7,5)
你如何构造你的向量并将a1存储到一个?我建议实现\uuu str\uuuuuuuuu
而不是\uuu repr\uuuu
。像内置类型一样repr
的类很难检测到。啊,是的,很好。让我来修!大家好!非常感谢你的帮助。这段代码运行得很好。还感谢您使用_repr_,我也将使用它。我不熟悉python类。再次感谢你的帮助。非常欢迎:)你好,非常感谢。我也尝试过这个,而且效果也很好。