help needed with class and method confusion
Robert Brewer
fumanchu at amor.org
Tue Jan 6 17:51:44 EST 2004
EricN wrote:
> Here's one way to do it (undoubtedly there are other ways as well).
> Sorry, I couldn't loop the moons. Probably a programmer more clever
> than I could write a factory pattern for it.
>
> class Moon:
> def __init__(self, name, diameter = 0.0, planet = "unknown"):
> self.NAME = name
> self.DIAMETER = diameter
> self.HOMEPLANET = planet
>
> def setMoonName(self, name):
> self.NAME = str(name)
>
> def getMoonName(self):
> return self.NAME
>
> def setMoonDiameter(self, diam):
> self.DIAMETER = float(diam)
>
> def getMoonDiameter(self):
> return self.DIAMETER
>
> def setMoonHomePlanet(self, planet):
> self.HOMEPLANET = str(planet)
>
> def getMoonHomePlanet(self):
> return self.HOMEPLANET
>
>
> if __name__ == "__main__":
> moons = []
> Io = Moon("Io", 1.0, "Jupiter")
> moons.append(Io)
> Europa = Moon("Europa", 2.0, "Jupiter")
> moons.append(Europa)
> Ganymeade = Moon("Ganymeade", 3.0, "Jupiter")
> moons.append(Ganymeade)
> Titan = Moon("Titan", 3.0, "Saturn")
> moons.append(Titan)
>
> for x in range(len(moons)):
> print moons[x].getMoonName()
> print moons[x].getMoonDiameter()
> print moons[x].getMoonHomePlanet()
> print
Wow. Someone's spent too much time writing Java. You can achieve the
same thing with far less cruft:
class Moon:
def __init__(self, name, diameter = 0.0, planet = "unknown"):
self.name = name
self.diameter = diameter
self.homeplanet = planet
if __name__ == "__main__":
moons = [Moon("Io", 1.0, "Jupiter"),
Moon("Europa", 2.0, "Jupiter"),
Moon("Ganymeade", 3.0, "Jupiter"),
Moon("Titan", 3.0, "Saturn"),
]
for moon in moons:
print moon.name
print moon.diameter
print moon.homeplanet
The biggest two changes stemming from the questions:
1) Why bother with all the setX/getX junk?
and
2) Why bother with variable names for each moon? Treat them anonymously.
FuManChu
More information about the Python-list
mailing list