UPDATE:
做多個構造的更多Python的方式是@classmethod
,由Jim的建議。 Raymond Hettinger在Pycon 2013上就Python的班級開發工具包進行了演講,在那裏他使用@classmethod
談論了multiple constructors。
class Line:
def __init__(self, a, b, noSlope):
self.a = a
self.b = b
self.noSlope = noSlope
@classmethod
def fromPoints(cls, point1, point2):
deltaX = point2[0] - point1[0]
deltaY = point2[1] - point1[1]
if deltaX == 0:
return cls(point1[0], 0, True)
else:
a = deltaY/deltaX
b = point1[1] - a * point1[0]
return cls(a, b, False)
@classmethod
def fromVector(cls, vector, point):
if vector[0] == 0:
return cls(point1[0], 0, True)
else:
a = vector[1]/vector[0]
b = point1[1] - a * point1[0]
return cls(a, b, False)
line = Line.fromPoints((0,0), (1,1))
到self
類似,cls
參數爲@classmethod
用作調用類隱式傳遞(在上面的例子中,這將是Line
)。這用於使用其他構造函數來適應未來的子類;它通過硬編碼基類來代替cls
,從而避免了意外繞過子類實現構造函數的潛在錯誤。
原貼:
如果要強制使用您的構造函數,你可以讓他們static methods,並讓他們回到你的類的實例。
class line:
def __init__(self, a, b, noSlope):
self.a = a
self.b = b
self.noSlope = noSlope
@staticmethod
def lineFromPoints(point1, point2):
deltaX = point2[0] - point1[0]
deltaY = point2[1] - point1[1]
if deltaX == 0:
return line(point1[0], 0, True)
else:
a = deltaY/deltaX
b = point1[1] - a * point1[0]
return line(a, b, False)
@staticmethod
def lineFromVector(vector, point):
if vector[0] == 0:
return line(point1[0], 0, True)
else:
a = vector[1]/vector[0]
b = point1[1] - a * point1[0]
return line(a, b, False)
# Create instance of class
myLine = line.lineFromPoints((0,0), (1,1))
編輯:
如果要強制使用您的構造函數在使用Line.__init__
,您可以使用下面的工廠隱藏線類直接實例:
class LineFactory:
class Line:
def __init__(self, a, b, noSlope):
self.a = a
self.b = b
self.noSlope = noSlope
@staticmethod
def fromPoints(point1, point2):
deltaX = point2[0] - point1[0]
deltaY = point2[1] - point1[1]
if deltaX == 0:
return LineFactory.Line(point1[0], 0, True)
else:
a = deltaY/deltaX
b = point1[1] - a * point1[0]
return LineFactory.Line(a, b, False)
@staticmethod
def fromVector(vector, point):
if vector[0] == 0:
return LineFactory.Line(point1[0], 0, True)
else:
a = vector[1]/vector[0]
b = point1[1] - a * point1[0]
return LineFactory.Line(a, b, False)
# Create line
line = LineFactory.fromPoints((0,0), (1,1))
由於這是一個Python問題,請刪除C#和C++代碼,因爲它無關,與你的問題 – BugFinder
謝謝。我只是做了 –
不知道你在問什麼具體問題,而且構造函數看起來很好,但是有一些非常突出的東西 - 類名總是大寫,所以稱之爲'class Line:'。對於所有這些索引查找('point1 [0]'等),你可以說'x1,y1 = point1'和'x2,y2 = point2',然後你的'deltaX'可以只是'x2-x1'後來你可以重複使用'x1,x2,y1,y2'等。基本上把你的符號想象成如果我試圖在紙上解決一些相似的數學方程,我該如何做到這一點。 – Bahrom