你有你的任務落後:
self.angle1 = angle1
等
關於正在發生的事情一點點可以幫助這裏的思考。 self
是在傳遞的類Triangle
的實例。所以,
T = Triangle()
T.method_call() #basically the same as `Triangle.method_call(T)`
在method_call
,self
是T
參考。 (__init__
是一種魔術 - 它得到的第一行自動調用,但原則仍然是相同的)。一旦你知道,這很容易理解爲什麼你需要self.whatever = whatever
- 你把一個新的屬性對象T
上!
最後,這說明你應該怎麼寫check_angles
:
def check_angles(self):
#remember, `self` is a reference to a triangle instance -- T in our hypothetical code
#so we can use `self` to gain access to all the attributes we set in `__init__`.
if self.angle1 + self.angle2 + self.angle3 == 180:
return True
else:
return False
現在快速轉入類屬性。你可以把屬性到類以及:
class Triangle:
number_of_sides = 3
我覺得這是習慣定義定義你的方法(函數)之前類屬性,但你實際上並不需要。 (這將有助於你的代碼的讀者,雖然明白 - 我誤解了,因爲你做事情的順序的原密碼)。
可以動態屬性添加到一個類的類已創建好以後:
class Triangle:
...
Triangle.number_of_angles = Rhombus.number_of_angles - 1
您可以訪問Triangle.some_attribute
幾種方法。第一種方式是直接通過課程(Triangle.number_of_sides
)。第二種方式是通過一個實例:
T = Triangle()
T.number_of_sides
起初這似乎有點有趣。畢竟,該實例沒有number_of_sides
屬性。事實證明,Python是設計看起來在實例第一,看它是否有它自己的number_of_sides
屬性。如果確實如此,那很好,那就是你得到的。但是,如果它不能,python會查看該類的屬性。這變成了一種便捷的方式來在一個類的實例之間共享數據。
不少東西,其實。 – NPE
檢查角度現在需要三個參數。 – Chriseyre2000
可能只是因爲更多的新手在嘗試學習Python而不是數學...... – martineau