# 创建一个坐标对象c = Coordinate(3, 4)# 计算到原点的距离print(c.distance_to_origin()) # 5.0# 打印坐标对象的字符串表示print(c) # (3, 4)# 实现坐标对象的加法c2 = Coordinate(1, 2)print(c + c2) # (4, 6)# 修改原点坐标Coordinate.set_origin(1, 1)print(c.origin) # (1, 1)# 删除坐标对象del c # Coordinate (3, 4) has been deleted.
时间: 2023-06-18 09:06:27 浏览: 47
以下是一个实现上述功能的示例代码:
```python
class Coordinate:
# 类变量,表示原点坐标
origin = (0, 0)
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to_origin(self):
return ((self.x - self.origin[0]) ** 2 + (self.y - self.origin[1]) ** 2) ** 0.5
def __str__(self):
return "({}, {})".format(self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Coordinate(x, y)
@classmethod
def set_origin(cls, x, y):
cls.origin = (x, y)
def __del__(self):
print("Coordinate {} has been deleted.".format(self))
```
你可以在 Python 中运行以下代码进行测试:
```python
# 创建一个坐标对象c = Coordinate(3, 4)
# 计算到原点的距离
print(c.distance_to_origin()) # 5.0
# 打印坐标对象的字符串表示
print(c) # (3, 4)
# 实现坐标对象的加法
c2 = Coordinate(1, 2)
print(c + c2) # (4, 6)
# 修改原点坐标
Coordinate.set_origin(1, 1)
print(c.origin) # (1, 1)
# 删除坐标对象
del c # Coordinate (3, 4) has been deleted.
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)