python - 在类中调用其他方法时缺少类属性
问题描述
我是所有这些东西的新手,所以请放轻松!
我写了一个类来计算各种向量结果。几个方法调用类中的其他方法来构造结果。除了一个特殊的问题外,大部分都可以正常工作。当我从另一种方法调用一个方法时,该方法的属性以某种方式被删除或丢失,我收到错误:AttributeError:'list' object has no attribute '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”。
欣赏人们在这里的见解。我不太了解技术术语,所以希望我能跟上。
解决方案
您试图将列表而不是 Vector 传递给您的dot_prod
方法(在 command 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
推荐阅读
- laravel - 你在哪里可以找到 Laravel 的调试信息?
- reactjs - 文本溢出:省略号不适用于 sass
- react-native - React Native ScrollView Ref 用于控制 scrollEnabled 道具
- reactjs - reactjs 渲染评论无法正常工作
- javascript - 沙箱化功能以使其安全?
- excel - 在 Excel 中编辑 R1C1 公式
- swift - Swift 访问辅助函数视图
- bash - 在 AWS @reboot 上运行脚本?
- r - 为什么ggplot2在点之间画一条垂直线?
- asp.net-mvc - ASP .NET Entity Framework 数据库未初始化