[Tutor] Creating multiple instance names
Jeff Shannon
jeff@ccvcorp.com
Fri Mar 14 13:11:02 2003
Lugo Teehalt wrote:
> Is it possible to use 'for' or 'while' or the like to create
>
> arbitrarilly many named class instances?
>
Yes, you can, but if you need to create a group of class instances, then
odds are that you're better off keeping them in some sort of collection
-- either a list or a dictionary.
>>> class Counter:
... def __init__(self):
... self.count = 0
... def incr(self):
... self.count += 1
...
>>> counters = {}
>>> for i in ['a', 'b', 'c', 'd']:
... counters[i] = Counter()
...
>>> counters['a']
<__main__.Counter instance at 0x01798378>
>>> counters['a'].incr()
>>> counters['a'].incr()
>>> counters['c'].incr()
>>> for name, ctr in counters.items():
... print "%s - %d" % (name, ctr.count)
...
a - 2
c - 1
b - 0
d - 0
>>>
While it's possible to futz about with exec and/or globals(), as Bob
Gailer suggested, I really don't recommend it. It will lead to code
that's hard to follow (because it makes it difficult to know what
is/will be in your namespace), which will lead to bugs. Those features
should be reserved for situations where nothing else works, and in this
situation a collection works splendidly -- I'd even argue that it works
*better*, by keeping your namespace cleaner and better-organized. It's
a good principle to never use black magic when it's not absolutely
necessary, and I consider both exec and (writing to) globals() to be
black magic -- or, as I've joked previously, at least very dark grey
magic. ;)
Jeff Shannon
Technician/Programmer
Credit International