Newbie question on Classes
John Machin
sjmachin at lexicon.net
Thu Jan 10 17:38:53 EST 2008
On Jan 11, 8:46 am, "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.
A class is a factory that creates objects. It keeps no records of what
it has created -- it will never have to recall them for remediation.
The customer needs to keep track of them.
[snip]
>I've
> tried tracking the names of each object in a list
In general, objects have 0, 1, or many "names" ... "tracking the
names" is not a very meaningful concept hence not a very useful
concept.
At your application level, a person's name is what they call
themselves and can vary over time and with the purpose for which it is
used, and what is actually recorded in databases is subject to a non-
trivial error rate -- hence using person's name as a key is not a very
good idea.
> 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.
"creating each object in a list" sounds like it's going down the right
path -- you need to keep a collection of objects somehow if you want
to perform some operations on all objects, and a list is a reasonable
start.
Here's a very basic simple skeleton toy demonstration:
>>> class Person(object):
... def __init__(self, name, hair):
... self.name = name
... self.hair = hair
... def show(self):
... print 'name=%r hair=%r' % (self.name, self.hair)
...
>>> plist = []
>>> obj1 = Person(name='Bluey', hair='red')
>>> plist.append(obj1)
>>> obj2 = Person(name='John', hair='grey')
>>> plist.append(obj2)
>>>
>>> for obj in plist:
... obj.show()
...
name='Bluey' hair='red'
name='John' hair='grey'
>>>
Does this help?
More information about the Python-list
mailing list