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