定义一个类 Pointe
时间: 2023-07-10 11:18:26 浏览: 47
好的,以下是定义一个类 Point 的示例代码:
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
self.x += dx
self.y += dy
def distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return (dx ** 2 + dy ** 2) ** 0.5
```
在上面的示例代码中,我们定义了一个名为 Point 的类,并赋予它以下三个方法:
- `__init__(self, x, y)`:这是类的构造函数,用于初始化对象的属性值。在本例中,我们传递两个参数 x 和 y,用于定义点的坐标。
- `move(self, dx, dy)`:这是一个实例方法,用于将点沿着 x 和 y 轴移动指定的距离 dx 和 dy。
- `distance(self, other)`:这也是一个实例方法,用于计算当前点与另一个点 other 之间的距离。
通过这个类,我们可以创建 Point 对象并使用其方法,例如:
```python
p1 = Point(0, 0)
p2 = Point(3, 4)
print(p1.distance(p2)) # 输出 5.0
p1.move(2, 3)
print(p1.x, p1.y) # 输出 2 3
```