Python类和错误

2024-04-25 21:11:42 发布

您现在位置:Python中文网/ 问答频道 /正文

现在做了一段时间的家庭作业,似乎还不知道如何绕过这个错误。只是要注意,我不允许进口任何东西

我得到的错误可能是由于我的__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)

Tags: oftheinselfbyreturndef错误
1条回答
网友
1楼 · 发布于 2024-04-25 21:11:42

您的self.pointlist属性是一个包含一个元组的列表:

def __init__(self, *vertices):
    # ....
    self.vertices = vertices
    self.pointlist = [self.vertices]

vertices在这里始终是一个元组,它依次包含Point()对象。元组从来没有xy属性;它本身不是Point实例

你也可以在这里用self.vertices代替self.pointlist。如果需要可变序列,请使用list()而不是列表文字:

self.pointlist = list(self.vertices)

它用元组中的元素创建一个列表

相关问题 更多 >