在定义的类中使用方法
问题描述:
我正在尝试制作一个脚本,我应该制作一个类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'
答
你永远不会实例化一个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)
答
您的代码:
point1 = (2,3,"red")
不会创建您的Dot类的实例 - 它只会创建一个tuple。
要创建一个点,你必须调用构造函数(__init__
),即:
point1 = Dot(2,3,"red")
我们在同一个班,我认为我得到了,你有同样的问题......没有他们答案解决了这个问题?因为他们没有修理我的 – holaprofesor 2015-04-01 23:46:04
@JaredBanton为什么不问你自己的问题呢? – Selcuk 2015-04-02 11:13:28