在Python中重写用户定义的向量类的加号运算符

2024-04-19 18:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个关于三维向量的类,如下所示

class vector(object):

def __init__(self, x=None, y=None, z=None, angle=None):

    if angle == None:
        self.x, self.y, self.z = x, y, z
    if angle != None:
        if angle == "rad":
            self.r, self.theta, self.phi = x, y, z
        if angle == "deg":
            self.r = x
            self.theta = y * 2 * pi / 360.
            self.phi = z * 2 * pi / 360.
        self.x = self.r * sin(self.theta) * cos(self.phi)
        self.y = self.r * sin(self.theta) * sin(self.phi)
        self.z = self.r * cos(self.theta)

def write(self):
    file.write("[" + str(self.x) + ",\t" + str(self.y) + ",\t" + str(self.z) + "]")

def write_sph(self):
    file.write("[" + str(self.mag()) + ",\t" + str(self.gettheta()) + ",\t" + str(self.getphi()) + "]")

def getx(self):
    return self.x
def gety(self):
    return self.y
def getz(self):
    return self.z

def setx(self, x):
    self.x = x
def sety(self, y):
    self.y = y
def setz(self, z):
    self.z = z

def square(self):
    return self.x*self.x + self.y*self.y + self.z*self.z
def mag(self):
    return sqrt(self.square())

def gettheta(self):
    return arccos(self.z / self.mag())
def getphi(self):
    return arctan2(self.y, self.x) # sign depends on which quadrant the coordinates are in

def __add__(self, vector(other)):
    v_sum = vector(other.gettx() + self.gettx(), other.getty() + self.getty(), other.getty() + self.getty())
    return v_sum

在上一个定义中,我试图重写加法运算符。该定义通过调用一个名为other的新向量,并将其x、y、z分量添加到self的相应分量中来实现。当我运行代码时,我被告知定义的语法无效。如何正确定义此重写定义的向量参数?另外,将定义从def uuuuuuu添加到def uuuuu添加会有什么不同?i、 下划线表示什么?你知道吗


Tags: selfnonereturnif定义def向量write
1条回答
网友
1楼 · 发布于 2024-04-19 18:28:48

参数列表中不应该有vector(other),只需说other。此外,您还需要修复add方法中的拼写错误:

def __add__(self, other):
    v_sum = vector(other.getx() + self.getx(), other.gety() + self.gety(), other.getz() + self.getz())
    return v_sum

相关问题 更多 >