简体   繁体   中英

Trying to understand how classes and objects interact with one another - python

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.planets contains all of the Planet objects, which do contain mass and such in addition to name . The reason it prints the planet's name when you try to print the planet is that print , in order to print something, first needs to convert the object to a string. It can do this by passing the object to the str function. The str function converts it by calling __str__ on the object. If you look at the definition of Planet , __str__ returns the planet's name, so when the planet is printed, its name is printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM