我是所有这些东西的新手,所以请放轻松我!
我写了一个类来计算各种矢量结果。有几种方法调用类中的其他方法来构造结果。除了一个特殊的问题,大部分工作都很好。当我从另一个方法调用一个方法时,该方法的属性以某种方式被删除或丢失,我得到错误:AttributeError:'list'对象没有属性'dot_prod',即使方法'dot_prod'在类中定义。我发现解决这个问题的唯一方法是使用原始方法调用的返回结果建立对象的新实例。在我的代码中,我通过注释开关包含问题代码和解决方法,以及上下文中的注释以尝试解释该问题。
from math import sqrt, acos, pi
class Vector:
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple([x for x in coordinates])
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
def scalar_mult(self, c):
new_coordinates = [c*x for x in self.coordinates]
return new_coordinates
def magnitude(self):
coord_squared = [x**2 for x in self.coordinates]
return sqrt(sum(coord_squared))
def normalize(self):
try:
mag = self.magnitude()
norm = self.scalar_mult(1.0/mag)
return norm
except ZeroDivisionError:
return 'Divide by zero error'
def dot_prod(self, v):
return sum([x*y for x,y in zip(self.coordinates, v.coordinates)])
def angle(self, v):
## This section below is identical to an instructor example using normalized unit
## vectors but it does not work, error indication is 'dot_prod' not
## valid attribute for list object as verified by print(dir(u1)). Instructor is using v2.7, I'm using v3.6.2.
## Performing the self.normalize and v.normalize calls removes the dot_prod and other methods from the return.
## My solution was to create new instances of Vector class object on self.normalize and v.normalize as shown below:
## u1 = self.normalize() # Non working case
## u2 = v.normalize() # Non working case
u1 = Vector(self.normalize())
u2 = Vector(v.normalize())
unit_dotprod = round((u1.dot_prod(u2)), 8)
print('Unit dot product:', unit_dotprod)
angle = acos(unit_dotprod)
return angle
#### Test Code #####
v1 = Vector([-7.579, -7.88])
v2 = Vector([22.737, 23.64])
print('Magnitude v1:', v1.magnitude())
print('Normalized v1:', v1.normalize())
print()
print('Magnitude v2:', v2.magnitude())
print('Normalized v2:', v2.normalize())
print()
print('Dot product:', v1.dot_prod(v2))
print('Angle_rad:', v1.angle(v2))
方法'angle(self,v)'是问题所在,据我所知,代码中的注释说明了一点。变量u1和u2有一个注释开关可以切换,你会看到在工作的情况下,我创建了Vector对象的新实例。我只是不知道原始方法调用中缺少属性的原因是什么。调用u1.dot_prod(u2)时的下一行是跟踪错误显示的位置,在非工作情况下通过执行dir(u1)验证属性中缺少'dot_prod'。
欣赏人们在这里的见解。我不太了解技术术语,所以希望我能跟进。
答案 0 :(得分:1)
您试图将列表而不是Vector传递给dot_prod
方法(在命令u2 = v.normalize()
;该方法的返回对象是一个列表)。我认为,您的问题是,您认为u2
会作为属性附加到类中,但您必须调用self
作为某些要点。有两种正确的方法可以调用方法并将输出重新附加为属性:
(1)您可以在实例化(创建)类之后调用它,如下所示:
vec = Vector([-7.579, -7.88])
vec.normal_coords = vec.normalize()
如果您不希望为每个Vector实例执行此操作,并且您不需要在许多其他方法中使用该属性,则此方法可以更好地工作。由于您需要使用标准化坐标来查找角度,我建议:
(2)在实例化期间作为属性附加(下面的长代码,以完全展示这将如何工作):
from math import sqrt, acos, pi
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple([x for x in coordinates])
self.dimension = len(coordinates)
# Next line is what you want - and it works, even though
# it *looks like* you haven't defined normalize() yet :)
self.normalized = self.normalize()
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
[...]
def dot_prod(self, v):
# v is class Vector here and in the angle() method
return sum([x*y for x,y in zip(self.normalized, v.normalized)])
def angle(self, v):
unit_dotprod = round((self.dot_prod(v)), 8)
print('Unit dot product:', unit_dotprod)
angle = acos(unit_dotprod)
return angle