Python 3.x 创建默认值
我有一个点类,它有2-d点实例。我还有一个震级函数,里面返回所说点的震级。下面是我的代码Python 3.x 创建默认值,python-3.x,Python 3.x,我有一个点类,它有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): # """
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)
您可以传递给初始值设定项,就像传递给任何其他函数一样
def __init__(self, x=0, y=0):
# """Initialize the Point instance"""
self.x = x
self.y = y