Python 无法在我的类中使用数学库函数
我正在为我的物理课程编写一个python类来处理向量。但是,由于某些原因,我无法从Python 无法在我的类中使用数学库函数,python,math,import,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 vecto
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)))
您能提供的任何帮助都是非常值得的这是有效的:
from math import sqrt, cos, sin, atan,degrees
class vector:
这是一个错误:
class vector:
from math import sqrt, cos, sin, atan,degrees
您还没有说实际发生了什么。这是您的实际代码,包括空格吗?类的内容应该是缩进的,这是真正的缩进吗?为什么导入在类中?当前目录中还有其他文件吗?他们中有人叫“math.py”吗?