无法在我的类中使用数学库函数

2024-04-19 18:50:14 发布

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

我正在为我的物理课程写一个python类来处理向量。但是,由于某些原因,我无法从math库访问函数。因为我不确定自己做错了什么,所以我只把全班的内容包括在内:

class vector:
from math import sqrt, cos, sin, atan,degrees
def __init__(self, x=0,y=0):
    self.components = (x,y)
    self.printmode = ('c')





#sets a preexisting vector to the given magnitude and direction
#uses cartesian rotation (+x is zero, goes counter-clockwise)
#Takes radians
def rotmag (self, magnitude, direction):
    self.components[0] = cos(direction) * magnitude
    self.components[1] = sin(direction) * magnitude

#this overrides the built-in addition function, so you can just
#add vector a and vector b by typing a+b.
def __add__(self,other):
    newX = self.components[0]+other.components[0]
    newY = self.components[1]+other.components[1]
    return vector(newX,newY)

#returns the rotation and direction of the specified vector
#returns a tuple, same standards as rotmag
def getrotmag (self) :
    mag = sqrt(self.components[0]**2+self.components[1]**2)
    dir = atan(self.components[1]/self.components[0])
    return (mag,dir)

def __str__(self):
    if(self.printmode == 'r'):
        tempray = self.getrotmag()
        return(str(round(tempray[0],4))+' @ '+str(round(tempray[1],4))+' radians')


    if(self.printmode == 'd'):
        tempray = self.getrotmag()
        return(str(round(degrees(tempray[0]),4))+' @ '+str(round(degrees(tempray[1]),4))+' radians')


    if(self.printmode == 'c'):
        return('x component: '+str(round(self.components[0],4))+'  y component: '+str(round(self.components[1],4)))

你能给予的任何帮助都是非常感激的


Tags: andtheselfreturndefcomponentsvectordegrees
1条回答
网友
1楼 · 发布于 2024-04-19 18:50:14

这是有效的:

from math import sqrt, cos, sin, atan,degrees
class vector:

这是一个错误:

class vector:
    from math import sqrt, cos, sin, atan,degrees

相关问题 更多 >