在 class 中调用其他方法时缺少 class 属性
Missing class attribute when calling other method in class
我是所有这些东西的新手所以请放轻松!
我写了一个class来计算各种矢量结果。一些方法调用 class 中的其他方法来构造结果。除了一个特殊的问题外,大部分工作正常。当我从另一个方法调用一个方法时,该方法的属性不知何故被删除或丢失,我得到错误:AttributeError: 'list' object has no attribute 'dot_prod', even though the method 'dot_prod' 在 class 中定义。我发现解决这个问题的唯一方法是使用原始方法调用的返回结果建立对象的新实例。在我的代码中,我通过注释开关包含了问题代码和变通方法,以及试图解释问题的上下文注释。
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
方法(在命令 u2 = v.normalize()
中;该方法的 return 对象是一个列表)。我认为,您的问题是您假定 u2
会作为属性附加到 class,但您必须调用 self
作为某个点才能做到这一点。调用方法并将输出重新附加为属性的正确方法有两种:
(1) 您可以在 class 被实例化(创建)之后调用它,如下所示:
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
我是所有这些东西的新手所以请放轻松!
我写了一个class来计算各种矢量结果。一些方法调用 class 中的其他方法来构造结果。除了一个特殊的问题外,大部分工作正常。当我从另一个方法调用一个方法时,该方法的属性不知何故被删除或丢失,我得到错误:AttributeError: 'list' object has no attribute 'dot_prod', even though the method 'dot_prod' 在 class 中定义。我发现解决这个问题的唯一方法是使用原始方法调用的返回结果建立对象的新实例。在我的代码中,我通过注释开关包含了问题代码和变通方法,以及试图解释问题的上下文注释。
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
方法(在命令 u2 = v.normalize()
中;该方法的 return 对象是一个列表)。我认为,您的问题是您假定 u2
会作为属性附加到 class,但您必须调用 self
作为某个点才能做到这一点。调用方法并将输出重新附加为属性的正确方法有两种:
(1) 您可以在 class 被实例化(创建)之后调用它,如下所示:
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