Newbie question on Classes

Nanjundi nanjundi at gmail.com
Thu Jan 10 17:06:49 EST 2008


On Jan 10, 4:46 pm, "Adrian Wood" <aaw... at gmail.com> wrote:
> Hi al! I'm new to the list, and reasonably new to Python, so be gentle.
>
> Long story short, I'm having a hard time finding a way to call a
> function on every object of a class at once. Example:
>
> I have a class Person, which has a function state(). This prints a
> basic string about the Person (position, for example). In the program,
> I have created two objects of class Person, called man and woman.
>
> 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.
>
> I'd appreciate anyone who could help, especially if they could include
> a short sample. My apologies if I'm not following the etiquette of the
> group in some way my making this request.
>
> Thank you,
> Adrian

Hi Adrian,
One easy way, is to append the objects to a list, as you have
mentioned and call the state method in iteration.
l = []
l.append(man)
l.append(woman)

# Print the state.
for item in l:
   print item.state()

(If I understood right, man and woman qualifies as "every instance of
man")
-N



More information about the Python-list mailing list