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

时间:2014-12-23 15:33:46

标签: python math import

我正在编写一个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)))

您可以提供的任何帮助都非常适用

1 个答案:

答案 0 :(得分:1)

这是有效的:

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

这是错误:

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