【发布时间】:2018-11-25 18:10:37
【问题描述】:
我是所有这些东西的新手,所以请放轻松!
我写了一个类来计算各种向量结果。几个方法调用类中的其他方法来构造结果。除了一个特殊的问题外,大部分都可以正常工作。当我从另一种方法调用一个方法时,该方法的属性以某种方式被删除或丢失,我收到错误:AttributeError:'list' object has no attribute 'dot_prod',即使方法'dot_prod'是在类中定义的.我发现解决此问题的唯一方法是使用原始方法调用的返回结果建立对象的新实例。在我的代码中,我包含了问题代码和通过注释开关的解决方法,以及上下文中的 cmets 以尝试解释问题。
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”。
欣赏人们在这里的见解。我不太了解技术术语,所以希望我能跟上。
【问题讨论】:
标签: python class-method class-attributes