2015-04-01 4 views
3

Я пытаюсь создать сценарий, в котором я должен сделать класс Dot, который занимает позицию X, позицию Y и цвет. Я сделал класс и все методы для этого. Проблема, с которой я сталкиваюсь, заключается в том, как применить метод. Вот что я сделал:Использование методов в определенном классе

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' 
+0

мы находимся в том же классе я думаю, и я получил ту же проблему, что вы имели ... сделал их ответы исправить проблему? потому что они не исправили мой – holaprofesor

+0

@ JaredBanton Почему бы вам не задать свой собственный вопрос? – Selcuk

ответ

3

Вы никогда не экземпляр 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) 
+0

Когда я меняю сценарий на свой, я получаю ошибку типа «Объект Dot» не поддерживает индексирование. Любая идея, почему это происходит? – Brett

+0

@Brett Вы также должны изменить строки 'print', как я предложил ... – Selcuk

0

Ваш код :

point1 = (2,3,"red") 

не создает экземпляр вашего класса Dot - он просто создает tuple.

Чтобы создать точку, вы должны вызвать его конструктор (__init__), то есть:

point1 = Dot(2,3,"red")