[英]Calling a method in a different class python
我执行了在矩形中移动点的功能,并且值均不返回,并且两个点均不返回。 当不想使用point方法时,我不想返回该值,是否还有其他选择。
class Point:
def move(self, dx, dy):
'''(Point,number,number)->None
changes the x and y coordinates by dx and dy'''
self.x += dx
self.y += dy
class Rectangle:
def move(self, dx, dy):
'''(Rectangle, number, number) -> None
changes the x and y coordinates by dx and dy'''
self.bottom_left = self.bottom_left.move(dx, dy)
self.top_right = self.top_right.move(dx, dy)
无需将结果分配回该点; Point.move
直接修改其参数,而不是返回新的Point
对象。
class Rectangle:
def move(self, dx, dy):
self.bottom_left.move(dx, dy)
self.top_right.move(dx, dy)
在矩形类中,如果用
self.corner = point.move(dx, dy)
Point.move()函数将需要返回某些内容,否则默认情况下不返回None。 您可以通过返回Point.move的自我来对此进行补救
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
'''(Point,number,number)->None
changes the x and y coordinates by dx and dy'''
self.x += dx
self.y += dy
return self
这样就解决了问题,而无需更改Rectangle代码。 你也可以
class Rectangle(object):
def __init__(self, top_right, bottom_left):
self.top_right = Point(*top_right)
self.bottom_left = Point(*bottom_left)
def move(self, dx, dy):
'''(Rectangle, number, number) -> None
changes the x and y coordinates by dx and dy'''
self.bottom_left.move(dx, dy)
self.top_right.move(dx, dy)
这可能会好一点,但是第一个示例说明了为什么您没有获得。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.