使用Python创建向量 [英] Creating Vectors with Python
问题描述
我创建一个向量类,其中一个参数是向量的长度。如果用户没有输入,则长度自动为0。例如: v(5)
会是 [0,0 ,0,0,0]
和 v()
将会是 []
。
这是我到目前为止的代码,但它不是很工作。任何建议?
I'm creating a vector class that has one parameter being the length of a vector. The length is automatically 0 if none is entered by user. If a vector is given a length, however, each number will be set to 0. For example: v(5)
would be [0,0,0,0,0]
and v()
would be []
.
This is the code i have thus far, but it's not quite working. Any advice?
class V:
def __init__(self, length = 0):
self.vector = [0]*length
def __str__(self):
print(self.vector)
def __len__(self):
return len(self.vector)
然后我插入 a = V 5)
并且当i 打印(a)
和 TypeError。任何建议?
Then i plug in a = V() b = V(5)
and when i print(a)
and print(b)
i get an TypeError. Any advice?
推荐答案
我可能会欺骗和去分类 list
:
I'd probably cheat and go for sub-classing list
:
class V(list):
def __init__(self, length=0):
super(V, self).__init__([0] * length)
<长度,repr和其他好东西免费。
This way you get the length, repr and other goodies for free.
这篇关于使用Python创建向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!