现在做了一段时间的家庭作业,似乎还不知道如何绕过这个错误。只是要注意,我不允许进口任何东西
我得到的错误可能是由于我的__repr__
或__str__
方法造成的。这是我的密码:
class Point:
def __init__(self, x = 0, y = 0):
"""
The constructor allows the user to set values for x and y. Default values are 0.
"""
self.x = x
self.y = y
def translate(self, s, t):
"""
This method translates point x by s and point y by t.
"""
self.x = self.x + s
self.y = self.y + t
return self.x, self.y
def __str__(self):
"""
This method returns a string representation of the point.
"""
return "({0}, {1})".format(self.x, self.y)
def __repr__(self):
"""
This method returns a string representation of the point.
"""
return "({0}, {1})".format(self.x, self.y)
class SimplePoly:
def __init__(self, *vertices):
"""
The constuctor adds all vertices to a list.
"""
self.vertices = vertices
self.pointlist = [self.vertices]
def translate(self, s, t):
"""
This method translates all points of the polygon by (s,t).
"""
for p in self.pointlist:
p.x + s
p.y + t
print(self.pointlist)
但是,当我尝试对self.pointlist中的每个点对象执行translate时,会出现以下错误:
Traceback (most recent call last):
File "<pyshell#170>", line 1, in <module>
h.translate(1,1)
File "C:/Python34/problem2.py", line 74, in translate
p.x + s
AttributeError: 'tuple' object has no attribute 'x'
顶点是点对象。这是我正在测试的代码:
>>> g = Point(2,3)
>>> g2 = Point(5,2)
>>> g3 = Point(6,7)
>>> h = SimplePoly(g,g2,g3)
>>> h.translate(1,1)
您的
self.pointlist
属性是一个包含一个元组的列表:vertices
在这里始终是一个元组,它依次包含Point()
对象。元组从来没有x
和y
属性;它本身不是Point
实例你也可以在这里用
self.vertices
代替self.pointlist
。如果需要可变序列,请使用list()
而不是列表文字:它用元组中的元素创建一个列表
相关问题 更多 >
编程相关推荐