help needed with class and method confusion

Sean Ross sross at connectmail.carleton.ca
Tue Jan 6 10:59:36 EST 2004


"Cndistin" <cndistin at aol.com> wrote in message
news:20040106102232.19889.00002028 at mb-m01.aol.com...
> The problem part of my code is
> class Application:
>     class Moon:
>         def __init__(self, name):
>             self.name = name
>     def __init__(self):
>         self.moons = []
>         names = ["Io", "Europa", "Ganymeade"]
>         for name in names:
>             setattr(self, name, Moon(name))
> I would like to somehow get self.moons to equal
> [self.Io, self.Europa, self.Ganymeade]. I had hoped on using
> self.moons as an iterant in "for" loops to be able to alter each
> in turn.
>
> Thanks in advance for any possible help.

class Application:
    class Moon:
        def __init__(self, name):
            self.name = name
        def __repr__(self):
            "added this to pretty up the printing of a.moons"
            return "Moon(%s)"%self.name

    def __init__(self):
        self.moons = []
        names = ["Io", "Europa", "Ganymeade"]
        for name in names:
            # took Moon(name) out of the setattr()  because we'll be
            # using it again in moons.append. Also used self.Moon
            # because Moon alone raises a NameError
            moon = self.Moon(name)
            setattr(self, name, moon)
            self.moons.append(moon)

a = Application()
print a.moons

# output
[Moon(Io), Moon(Europa), Moon(Ganymeade)]

HTH
Sean





More information about the Python-list mailing list