在不同的python类中调用方法

在不同的python类中调用方法,python,class,methods,call,Python,Class,Methods,Call,我执行了移动矩形中的点的函数,这些值返回none和none。我不想在首选点中的方法时返回值,是否有其他选项 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 Rectang

我执行了移动矩形中的点的函数,这些值返回none和none。我不想在首选点中的方法时返回值,是否有其他选项

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)

在矩形类中,如果使用

self.corner = point.move(dx, dy)
函数Point.move()需要返回一些内容,否则默认情况下不返回任何内容。您可以通过返回点的self.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
这在不更改矩形代码的情况下解决了问题。你也可以这样做

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)

这可能稍微好一点,但第一个示例解释了为什么没有得到任何结果。

在矩形类中,如果使用

self.corner = point.move(dx, dy)
函数Point.move()需要返回一些内容,否则默认情况下不返回任何内容。您可以通过返回点的self.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
这在不更改矩形代码的情况下解决了问题。你也可以这样做

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)

这可能稍微好一点,但第一个示例解释了为什么没有得到任何结果。

没有必要将结果分配回该点<代码>点。移动直接修改其参数,而不是返回新的
对象

class Rectangle:
    def move(self, dx, dy):
        self.bottom_left.move(dx, dy)
        self.top_right.move(dx, dy)

不需要将结果分配回该点<代码>点。移动直接修改其参数,而不是返回新的
对象

class Rectangle:
    def move(self, dx, dy):
        self.bottom_left.move(dx, dy)
        self.top_right.move(dx, dy)