Python类:移动矩形
您好,我正在尝试使这个矩形移动到某些坐标,而不改变矩形的宽度和高度。当我使用Python类:移动矩形,python,Python,您好,我正在尝试使这个矩形移动到某些坐标,而不改变矩形的宽度和高度。当我使用\uuu str\uu方法时,我没有得到正确的答案。你知道怎么回事吗?这是我的密码 class Rectangle(object): def __init__(self,corner,width,height): self._x = corner[0] self._y = corner[1] self._width = width self._height = height de
\uuu str\uu
方法时,我没有得到正确的答案。你知道怎么回事吗?这是我的密码
class Rectangle(object):
def __init__(self,corner,width,height):
self._x = corner[0]
self._y = corner[1]
self._width = width
self._height = height
def get_bottom_right(self):
self._width = self._x + self._width
self._height = self._y + self._height
return(self._width,self._height)
def move(self,p):
self._p = self._x, self._y
def resize(self,width,height):
resize = self._width + self._height
return(resize)
def __str__(self):
return '({0}, {1})'.format((self._x, self._y), (self._x + self._width, self._y + self._height))
我不确定您想要如何移动矩形,但我知道您的
move
和resize
方法目前没有任何作用
当前,move方法所做的是接受一个名为p
的参数,然后继续忽略该参数。然后,它在矩形内创建一个名为\u p
的新字段,并将\u p
设置为其x和y坐标。但是,这也是一个无用的操作,因为您从未使用过\u p
,也从未实际移动过变量
相反,您可能希望执行以下操作:
def move(self, x, y):
self._x = x
self._y = y
现在,如果执行我的矩形。移动(3,4)
,则我的矩形的x和y坐标将更改为3和4
如果p
是一个类似于“点”的对象,那么您可能需要这样做:
def move(self, p):
self._x = p.x
self._y = p.y
def resize(self, width, height):
self._width = width
self._height = height
同样,您的“调整大小”方法也没有做任何有意义的事情。调用它只会返回矩形的宽度和高度之和,这实际上并不意味着什么。您可能希望将其改为:
def move(self, p):
self._x = p.x
self._y = p.y
def resize(self, width, height):
self._width = width
self._height = height
您的move
方法不会修改正确的属性来移动矩形。您希望使用传入的p
参数来修改self.\ux
和self.\uy
而不是分配给self.\up
试试这个:
def move(self,p):
self._x, self._y = p
这会将矩形移动到点p
(假设p
是(x,y)
元组)。如果要按p
移动,请尝试:
def move(self,p):
self._x += p[0]
self._y += p[1]
resize
方法中也存在类似问题(您希望修改self.\u width
和self.\u height
,而不是将它们添加在一起并返回它们)。get\u bottom\u right
方法有相反的问题,因为它修改了self.\u width
和self.\u height
,而它可能不应该修改。您的move()
函数看起来是错误的。它接受一个名为p
(我假设为“pair”)的参数,我假设它将矩形移动到这些坐标。但它根本没有改变自我。我认为你在这个函数中得到了你的赋值,你可能想做:
def move(self,p):
self._x, self._y = p
def move(self,p):
self._x = p.x
self._y = p.y
如果p是一个元组(一个(3,4)
对)。如果它是具有x
和y
属性的对象,则需要执行以下操作:
def move(self,p):
self._x, self._y = p
def move(self,p):
self._x = p.x
self._y = p.y
正如其他人已经指出的那样
实际上,除了这个问题之外,您的代码还有其他几个问题。你的get\u bottom\u right()
函数正在更改self.\u width
和self.\u height
,这不是你想要的,你的resize()
函数根本没有更改self.\u width
和self.\u height
的值
。。。我看到其他人指出了move()
和resize()
函数中的错误,因此我将处理get\u bottom\u right()
函数。您可能想这样做:
def get_bottom_right(self):
right = self._x + self._width
bottom = self._y + self._height
return (right,bottom)
请注意,我只是更改了变量名,但您的代码在其他方面保持不变。这将实现您想要的功能,而不会在过程中更改矩形的宽度和高度。每次调用get\u bottom\u right()
什么是“正确答案”,您的原始代码都会更改宽度和高度?你得到了什么答案?向我们展示您为Rectangle
实例提供的输入。作为旁注,如果您在掌握更改状态的诀窍方面遇到问题,也许您应该首先尝试编写非变异函数,如moved(self,p)
返回一个新的Rectangle
的Rectangle
。思考返回矩形(…)
中发生的事情比思考self中发生的事情要容易得多。_foo=…
。是的,这对我很有用。非常感谢。我现在明白了,我的函数什么都没做,哈哈