2016-10-22 71 views
0

我對學校的任務有問題。我想要我的最後一種方法來測試兩個矩形是否相同。唯一的問題是,我似乎無法區分兩個不同矩形的兩個不同高度,widiths和不同點(這是矩形的左下角點),有什麼建議嗎?Python:如何區分同一類中兩個不同對象的兩個變量?

非常感謝

class Point(): 
    def __init__(self,x,y): 
     self.x=x 
     self.y=y 

class Rectangle(): 
    def __init__(self,Point,w,h): 
     self.Point=Point 
     self.widith=w**strong text** 
     self.height=h 

    def same(self,Rectangle): 
     if Rectangle.self.Point==self.Point and Rectangle.self.widith==self.widith and Rectangle.self.height==self.height: 
      return True 
     else: 
      return False 
+0

我不會使用'Point'參數'(__init __(self,Point ...)'和'class Point'(我會做'__init __(self,point, w,h)')然後我會看看該類的'__eq__'方法(https://docs.python.org/2/reference/datamodel.html#object.__eq__)。如果你在'Point'和'Rectangle'類中覆蓋它,你可以使用'rectangle1 == rectangle2' – BorrajaX

回答

2

首先,沒有爲功能PARAMS和類使用相同的名稱。它使代碼混淆並容易出錯。試試這個:

class Rectangle: 
    def __init__(self, point, width, height): 
     self.point = point 
     self.widith = width 
     self.height = height 

現在我認爲point變量是Point類的一個實例。在這種情況下,通過==通過==比較一個點將會失敗,因爲默認==檢查兩個對象在內存中是否是同一個對象。

因此您same方法implemenatation可能看起來像這樣:

def same(self, other): 
    return (
     self.point.x == other.point.x 
     and self.point.y == other.point.y 
     and self.width == other.width 
     and self.height == other.height 
    ) 

如果覆蓋內置__eq__方法(它負責==運營商的行爲)上Point類是這樣的:

class Point: 
    def __init__(self, x, y): 
     self.x = x 
     self.y = y 
    def __eq__(self, other): 
     return self.x == other.x and self.y == other.y 

然後same方法可以簡化爲:

def same(self, other): 
    return (
     self.point == other.point # now __eq__ will be called here 
     and self.width == other.width 
     and self.height == other.height 
    ) 
+0

謝謝你,我爲你做了。 –

相關問題