我一直在尋找如何在 Python 類中宣告一個方法,這與 Java 和 C 將型別別作為引數的方式等效,就像在復制建構式方法中一樣。
Java類:
class Point {
protected float x;
protected float y;
public Point() {
this.x = 0.0f; this.y = 0.0f;
}
public Point( Point p ) {
this.x = p.x; this.y = p.y;
}
public boolean isEqual( Point p ) {
return this.x == p.x && this.y == p.y;
}
public void setValues( float x, float y ) {
this.x = x; this.y = y;
}
public void setValues( Point p ) {
this.x = p.x; this.y = p.y;
}
}
這是我到目前為止所使用的 Python 類:
class Point:
def __init__(self):
self.x = 0.0;
self.y = 0.0;
def setValues( x, y ):
self.x = x
self.y = y
#def __init__( Point ): how to pass an instance of this class to copy the values?
#def isEquals( Point ): this would return True or False if the values are both equal.
#def setValues( Point ): how to pass an instance of Point?
我不熟悉 Python,所以我不確定如何定義一個將其型別別作為引數的成員函式。復制建構式或 Java 代碼中定義的 isEqual() 方法的 Python 等價物是什么?
謝謝。
uj5u.com熱心網友回復:
Python 不是強型別語言。這意味著函式不會專門采用任何特定型別的實體。您始終可以將任何物件傳遞給任何函式!
當然,如果您傳遞的物件沒有正確的方法或屬性,那么它將無法正常作業。
它不完全是pythonic,但如果你真的想確保你只獲得 type 的物件Point,你可以嘗試類似的東西
def setValues( self, point ):
if not isInstance( point, Point ):
# Assert? Return? Throw an exception? Up to you!
self.x = point.x
self.y = point.y
如果你想進一步閱讀這個主題,這個過去的問題有一些很好的材料。
uj5u.com熱心網友回復:
你可以看到這個鏈接,也許它會在某種程度上有所幫助。這里
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/310959.html
