[英]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.