I am working through the examples from “Python Programming in Context” my Miller & Ranum.
I am working through the section on classes and we are building a solar system, and I am not clear on one certain part of the code.
class SolarSystem:
def __init__(self, asun):
self.thesun = asun
self.planets = []
def add_planet(self, aplanet):
self.planets.append(aplanet)
def show_planets(self):
for aplanet in self.planets:
print(aplanet)
def num_planets(self):
return len(self.planets)
I am not really sure how the add_planet and show_planets methods work exactly. In the shell I created a some planets using the “Planet” class. The planet class has more parameters than just name. It also includes name, radius, mass, distance from the sun and number of moons. When I pass a planet object to the SolarSystem class does the self.planets list contain all the arguments that were passed to the Planet object? If so how does the show_planet method know to print out the just names of planets? I think i may have missed something crucial here, one of the questions is to add a method for summing up the total mass in the solar system. But I am not sure how to access the instance variable for mass from the Planets class so I can sum them in the SolarSystem class.
I hosted a repository on github since there is more than one file and I didn’t want to paste it all here. solarsystem That way you can see what I am talking about.
I hope this makes sense, just ask if you’re unclear on anything.
Thanks
I added a total_mass method
def total_mass(self):
total_mass = 0
for aplanet in self.planets:
total_mass = total_mass + get_mass(aplanet)
return total_mass
It didn’t work and I am not sure why.
I got it!
The last line should be:
total_mass = total_mass + aplanet.get_mass()
self.planetscontains all of thePlanetobjects, which do containmassand such in addition toname. The reason it prints the planet’s name when you try to print the planet is thatprint, in order to print something, first needs to convert the object to a string. It can do this by passing the object to thestrfunction. Thestrfunction converts it by calling__str__on the object. If you look at the definition ofPlanet,__str__returns the planet’s name, so when the planet is printed, its name is printed.