Newbie question on Classes

Steven Clark steven.p.clark at gmail.com
Thu Jan 10 17:02:53 EST 2008


On Jan 10, 2008 4:54 PM, Fredrik Lundh <fredrik at pythonware.com> wrote:

> Adrian Wood wrote:
>
> > I can call man.state() and then woman.state() or Person.state(man) and
> > Person.state(woman) to print the status of each. This takes time and
> > space however, and becomes unmanageable if we start talking about a
> > large number of objects, and unworkable if there is an unknown number.
> > What I'm after is a way to call the status of every instance of Man,
> > without knowing their exact names or number.
> >
> > I've gone through the relevant parts of the online docs, tried to find
> > information elsewhere online, and looked for code samples, but the
> > ionformation either isn't there, or just isn't clicking with me. I've
> > tried tracking the names of each object in a list, and even creating
> > each object within a list, but don't seem to be able to find the right
> > syntax to make it all work.
>
> For a start, how about:
>
>     class Person:
>         ... your class ...
>
>     persons = []
>
>     man = Person()
>     persons.add(man)
>
>     woman = Person()
>     persons.add(woman)
>
>     for p in persons:
>         print p, p.state()
>
> Once you've gotten this to work, you can, if you want, look into moving
> the list maintenance into the class itself (i.e. let the __init__
> function add the person to the list, and provide a destroy method that
> removes it from the list).  And once you've gotten that to work, you can
> look at the "weakref" module for more elegant ways to handle
> destruction.  But one step at a time...
>
> </F>
>
> -- <http://mail.python.org/mailman/listinfo/python-list>
>


if you can keep all instances in a list, as Fredrik showed, it's easy.
Otherwise you can do something like:

class Person:
    people = []
    def __init__(self, name):
        self.name = name
        Person.people.append(self)

    def print_state(self):
        print self.name

some_folks = [Person('Bob'), Person('Mary')]
other_guy = Person('Frank')

for p in Person.people:
    p.print_state()


This would keep the people from ever being garbage collected, but this may
not be a problem for you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080110/cc346f26/attachment-0001.html>


More information about the Python-list mailing list