2015-04-01 105 views
3

我正在嘗試製作一個腳本,我應該製作一個類Dot,它需要X位置,Y位置和Color。我已經讓班級和所有的方法都一起去了。我遇到的問題是如何應用該方法。這是我做了什麼:在定義的類中使用方法

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 2015-04-01 23:46:04

+0

@JaredBanton爲什麼不問你自己的問題呢? – Selcuk 2015-04-02 11:13:28

回答

3

你永遠不會實例化一個Dot對象,創建具有三個元素的元組。將其更改爲:

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

當我將腳本更改爲您的腳本時,我收到類型錯誤「點」對象不支持索引。任何想法爲什麼發生這種情況? – Brett 2015-04-01 21:12:19

+0

@Brett你也應該改變'print'行,正如我所建議的那樣...... – Selcuk 2015-04-01 21:12:50

0

您的代碼:

point1 = (2,3,"red") 

不會創建您的Dot類的實例 - 它只會創建一個tuple

要創建一個點,你必須調用構造函數(__init__),即:

point1 = Dot(2,3,"red") 
相關問題