Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python为n维向量创建一个类。不允许使用Numpy、scipy和类似产品_Python_Class_Vector - Fatal编程技术网

用python为n维向量创建一个类。不允许使用Numpy、scipy和类似产品

用python为n维向量创建一个类。不允许使用Numpy、scipy和类似产品,python,class,vector,Python,Class,Vector,关于创建一个类来计算n维向量的常见运算(求和、点积、叉积等),我请求您的帮助 我刚开始就有问题: class nVector: ''' Our goal is o create a class to work with nD vectors''' def __init__(self,*args): '''Construction of the nD vector with n arguments''' r=[] '''empty

关于创建一个类来计算n维向量的常见运算(求和、点积、叉积等),我请求您的帮助

我刚开始就有问题:

class  nVector:
    ''' Our goal is o create a class to work with nD vectors'''
    def __init__(self,*args):
        '''Construction of the nD vector with n arguments'''
        r=[]
        '''empty list where the coordinates will be gathered'''
        for i,xi in enumerate(args): 
            self.i=xi
            r=r+[xi]
        self.r=r


        return 

后来我用r列表把它串起来,然后可以打印出来并看到一些东西。主要问题是,如果我在终端中写入self.1,我希望得到第一个坐标,self.2第二个坐标,依此类推,但它返回错误:


n=nVector(1,1,1,1)

n.1
  File "<ipython-input-9-a30c5b21dbaf>", line 1
    n.1
      ^
SyntaxError: invalid syntax

n=nVector(1,1,1,1)
n、 一,
文件“”,第1行
n、 一,
^
SyntaxError:无效语法
谁知道怎么才能把它修好

另一个问题是,我没有执行向量求和的线索


感谢大家

当前的问题是“如果我在终端中写入self.1,我希望得到第一个坐标”。你是从哪里得到这个想法的;这不是合法的Python语法。这里的点运算符用于
class.attribute
access,整数不是合法的属性name

我想你想要的是
n.r[0]
n.r[1]
,等等

用几个简单的
print
命令跟踪您所写的内容:

class  nVector:
    ''' Our goal is o create a class to work with nD vectors'''
    def __init__(self,*args):
        '''Construction of the nD vector with n arguments'''
        r=[]
        '''empty list where the coordinates will be gathered'''
        for i,xi in enumerate(args): 
            self.i=xi
            print("attribute i", self.i)
            r=r+[xi]
        self.r=r
        print("attribute r", self.r)


        return 

n=nVector(1,2,3,4)

print(n.i)
输出:

attribute i 1
attribute i 2
attribute i 3
attribute i 4
attribute r [1, 2, 3, 4]
4

这有助于弄清类属性是如何工作的吗?

想想
self.i=xi
在循环中做了什么。这就是你想做的吗?您是否应该以某种方式使用
r
self.r
在类中对应于
n.r
外部,您希望
n.1
做什么,因为它不是有效的python语法
n.r[1]
可能会更接近你想要的。如果你键入
n.i
你将得到
1
,如果你这样做
n=nVector(1,2,3)
n.i
将是3。这是因为未计算
n.i
中的
i
。您确实创建了属性
i
,并在for循环的每次迭代中将其设置为不同的值。您明确表示不允许使用相关库的部分使我非常怀疑这是家庭作业,因此我将引用“3.要求家庭作业帮助的问题必须包括到目前为止你为解决问题所做工作的总结,以及对你解决问题的困难的描述。“因此,对于其他操作部分,如果没有更多的输入,我们将不会为您提供解决方案。提示:您正在寻找的方法是
\uuuuu getitem\uuuuuuuu
\uuuuuu setitem\uuuuu
。剩下的你应该自己解决。