如何理解 Python 中的简单断言语句,移动 Point 实例
How to understand a simple assert statement in Python, moving a Point instance
我为点 class 及其方法编写了以下代码。我想知道如何应用 assert 语句来测试 Point x, y 坐标是否正确移动。我假设 assert 语句在将 move 方法应用于 Point 实例后测试结果坐标的有效性。你能建议我应该如何编写一个断言语句来验证点 class 的所有给定实例是否已正确移动吗?
class Point(object): # Modify here
#Creates a point on the x,y coordinate system
def __init__(self,x,y):# The __init__ constructor takes the arguments self( the current instance of the class), and positions x and y
#Defines x and y variables
self.x = x # Define self's x attribute.
self.y = y
#Moves the given point by dx and dy
def move(self,dx,dy):#
#Move the point to different location
self.x=self.x+dx# the self's x + change in x
self.y=self.y+dy
#returns string representation of class Point
def __str__(self,x,y):
return "Point location:",(self.x,self.y)
if __name__ == '__main__':
# Tests for point
# ==================================
def testPoint(x, y):
p = Point(0, -1) # create a point instance
p.move(2, 2) # Use method move, move the point object by x=2 and y=2
assert p.x == 2
assert p.y ==1
print 'Success! Point tests passed!'
testPoint(0,-1)
这是您需要的吗 -- 为给定输入参数化的方法?
def testPoint(x, y, move_x, move_y):
p = Point(x, y) # create a point instance
p.move(move_x, move_y) # Use method move, move the point object by x=2 and y=2
assert p.x == x + move_x and \
p.y == y + move_y
然后您可以针对各种起点和运动向量执行此操作。
我为点 class 及其方法编写了以下代码。我想知道如何应用 assert 语句来测试 Point x, y 坐标是否正确移动。我假设 assert 语句在将 move 方法应用于 Point 实例后测试结果坐标的有效性。你能建议我应该如何编写一个断言语句来验证点 class 的所有给定实例是否已正确移动吗?
class Point(object): # Modify here
#Creates a point on the x,y coordinate system
def __init__(self,x,y):# The __init__ constructor takes the arguments self( the current instance of the class), and positions x and y
#Defines x and y variables
self.x = x # Define self's x attribute.
self.y = y
#Moves the given point by dx and dy
def move(self,dx,dy):#
#Move the point to different location
self.x=self.x+dx# the self's x + change in x
self.y=self.y+dy
#returns string representation of class Point
def __str__(self,x,y):
return "Point location:",(self.x,self.y)
if __name__ == '__main__':
# Tests for point
# ==================================
def testPoint(x, y):
p = Point(0, -1) # create a point instance
p.move(2, 2) # Use method move, move the point object by x=2 and y=2
assert p.x == 2
assert p.y ==1
print 'Success! Point tests passed!'
testPoint(0,-1)
这是您需要的吗 -- 为给定输入参数化的方法?
def testPoint(x, y, move_x, move_y):
p = Point(x, y) # create a point instance
p.move(move_x, move_y) # Use method move, move the point object by x=2 and y=2
assert p.x == x + move_x and \
p.y == y + move_y
然后您可以针对各种起点和运动向量执行此操作。