我有一个具有2-d点实例的点类。我内部还有一个幅度函数,该函数返回所述点的幅度。下面是我的代码...
class Point:
# """2-D Point objects."""
def __init__(self, x, y):
# """Initialize the Point instance"""
self.x = x
self.y = y
def get_magnitude(self):
# """Return the magnitude of vector from (0,0) to self."""
return math.sqrt(self.x ** 2 + self.y ** 2)
def __str__(self):
return 'Point at ({}, {})'.format(self.x,self.y)
def __repr__(self):
return "Point(x={},y={})".format(self.x,self.y)
point = Point(x=3, y=4)
print(str(point))
print(repr(point))
print(point)
...完成所有这些操作后,最后一步是实现默认点(0,0)。有关如何执行此操作的任何建议?它应该像这样...
point2 = Point()
print(point2)
Point(x=0, y=0)
point3 = Point(y=9)
print(point3)
Point(x=0, y=9)
答案 0 :(得分:1)
您可以将default arguments传递给初始化程序,就像其他任何函数一样。
def __init__(self, x=0, y=0):
# """Initialize the Point instance"""
self.x = x
self.y = y