|
|
class Planet:
def __init__(self, name, planet_type, star):
# 檢查參數是否為字串
if not all(isinstance(arg, str) for arg in (name, planet_type, star)):
raise TypeError("name, planet type, and star must be strings")
# 檢查參數是否為空字串
if not all(arg.strip() for arg in (name, planet_type, star)):
raise ValueError("name, planet_type, and star must be non-empty strings")
# 設定實體屬性
self.name = name
self.planet_type = planet_type
self.star = star
# 行星繞恆星運行
def orbit(self):
return f"{self.name} is orbiting around {self.star}..."
# 回傳行星資訊
def __str__(self):
return f"Planet: {self.name} | Type: {self.planet_type} | Star: {self.star}"
# 建立三個行星實體
planet_1 = Planet("Earth", "Terrestrial", "Sun")
planet_2 = Planet("Jupiter", "Gas Giant", "Sun")
planet_3 = Planet("Neptune", "Ice Giant", "Sun")
# 列印行星資訊
print(planet_1)
print(planet_2)
print(planet_3)
# 列印行星運行資訊
print(planet_1.orbit())
print(planet_2.orbit())
print(planet_3.orbit())
|
|