设计一个行星类。每个行星都有一个名称、半径、质量和离太阳的距离。要求设计: (1)分别设计四个属性名称、半径、质量和离太阳的距离的访问器方法和修改器方法。 (2)设计一个方法返回行星的体积。 (3)设计一个方法返回行星表面积。 (4)设计一个方法返回行星密度。 (5)设计一个__str()__方法,返回对行星的描述,输出行星的名称、体积、表面积和行星密度 编写一个测试程序,输入行星的名称、半径、质量和距离,输出相应的信息
时间: 2023-06-08 15:09:19 浏览: 435
CSDN ChitGPT: 好的,请问您想使用什么编程语言来实现这个行星类呢?
我:Python。
CSDN ChitGPT: 好的,以下是用Python实现的代码,请您先过目一下:
```python
import math
class Planet:
def __init__(self, name, radius, mass, distance):
self.__name = name
self.__radius = radius
self.__mass = mass
self.__distance = distance
def get_name(self):
return self.__name
def get_radius(self):
return self.__radius
def get_mass(self):
return self.__mass
def get_distance(self):
return self.__distance
def set_name(self, new_name):
self.__name = new_name
def set_radius(self, new_radius):
self.__radius = new_radius
def set_mass(self, new_mass):
self.__mass = new_mass
def set_distance(self, new_distance):
self.__distance = new_distance
def get_volume(self):
volume = (4/3) * math.pi * self.__radius ** 3
return round(volume, 2)
def get_surface_area(self):
area = 4 * math.pi * self.__radius ** 2
return round(area, 2)
def get_density(self):
density = self.__mass / self.get_volume()
return round(density, 2)
def __str__(self):
return "Planet Name: {}\nVolume: {} cubic meters\nSurface Area: {} square meters\nDensity: {} kg/{}, respectively".format(self.get_name(), self.get_volume(), self.get_surface_area(), "cubic meter", self.get_density())
planet_name = input("Input name of planet: ")
planet_radius = float(input("Input radius of planet in meters: "))
planet_mass = float(input("Input mass of planet in kilograms: "))
planet_distance = float(input("Input distance of planet to the sun in meters: "))
p = Planet(planet_name, planet_radius, planet_mass, planet_distance)
print(p)
```
我:这段代码看上去很好,我可以使用它吗?
CSDN ChitGPT: 当然可以,你可以将它复制粘贴到你的Python编辑器中进行测试。如果有问题,随时与我取得联系。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)