python - 在定义的类中使用方法

标签 python class methods

我正在尝试制作一个脚本,我应该在其中制作一个 Dot 类,它采用 X 位置、Y 位置和颜色。我已经制作了类(class)和所有与之配套的方法。我遇到的问题是如何应用该方法。这是我所做的:

class Dot:
    '''A class that stores information about a dot on a flat grid
       attributes: X (int) Y (int), C (str)'''

    def __init__(self, xposition, yposition, color):
        '''xposition represents the x cooridinate, yposition represents
           y coordinate and color represent the color of the dot'''
        self.X = xposition
        self.Y = yposition
        self.C = color


    def __str__(self):
        "Creates a string for appropiate display to represent a point"
        return str(self.X) + " " + str(self.Y) + " " + str(self.C)

    def move_up(self,number):
        '''Takes an integer and modifies the point by adding the given
           number to the x-coordinate
           attributes: number (int)'''

        self.Y = number + self.Y

    def move_right(self,number):
        '''Takes an integer and modifies the Point by adding the given number to the y-coordinate
           attributes: number (int)'''

        self.X = number + self.X

    def distance_to(point2):
        '''Takes another Dot and returns the distance to that second Dot
           attributes: X (int) Y (int)'''

        distance = ((self.X - point2.X )**2) + ((self.Y - point2.Y)**2)
        real_distance = distance.sqrt(2)

        return real_distance



point1 = (2,3,"red")
print("Creates a" + " " + str(point1[2]) + " " + "dot with coordinates (" + str(point1[0]) + "," + str(point1[1]) + ")")
point2 = (1,2,"blue")
print("Creates a" + " " + str(point2[2]) + " " + "dot with coordinates (" + str(point2[0]) + "," + str(point2[1]) + ")")
new_point = point1.move_up(3)
print("Moves point up three on the y axis")

这是返回的内容:

AttributeError: 'tuple' object has no attribute 'move_up'

最佳答案

您永远不会实例化 Dot 对象,您创建了一个包含 3 个元素的元组。将其更改为:

point1 = Dot(2,3,"red")
point2 = Dot(1,2,"blue")

而不是

print("Creates a" + " " + str(point1[2]) + " " + "dot with coordinates (" + str(point1[0]) + "," + str(point1[1]) + ")")

使用

print "Creates a" + " " + point1.C + " " + "dot with coordinates (" + str(point1.X) + "," + str(point1.Y) + ")"

顺便说一句,.format() 语法更清晰:

print "Creates a {0} dot with coordinates ({1}, {2})".format(point1.C, point1.X, point1.Y)

关于python - 在定义的类中使用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29400797/

相关文章:

php - 如何在 PHP 中合并两个类?

java - 调用方法并传递对象引用并使用相同的引用捕获返回

python - mariadb 的简单多行 SQL 查询中的 pymysql.err.ProgrammingError 1064

python - PyQt类继承

python - 按另一个矩阵排序在一种情况下有效,但在另一种情况下失败

css - 将不同的 css 样式类分配给已经存在的 css 类

javascript - 如何停止循环数组的方法?

java - 为什么我的编译器一直说我有一个 catch block ,而没有前面的 try block

python - 按 'Date' 分组,同时计算其他列的平均值

python - 如何在 “stack overflow error”之后自动重新运行python代码