[Tutor] Creating & Handling lots of objects

Alan Gauld alan.gauld at freenet.co.uk
Sat Dec 4 01:14:43 CET 2004


> I've written a class, with some methods. I then want to be able to
call
> the class repeatedly, to create some objects. The number of objects,
and
> some of their initialisation parameters need to be specified later
(i.e.
> at run-time).

Not quite sure what you mean by the last bit but I'll come
back to that...

> When I generate all these objects, how do I keep track of them.

Check out the OOP topic in my tutor, it discusses this within the
context
of a bank account example - how to manage large numbers of account
holders.

The short answer is put them in a list or dictionary.

> but this is obviously not scaleable. If I use a list, I can do:
> ...
> but then I have to search the list (MyObjects) for the object where
> Object.name="a".
>
> The only other option seems to be finding objects via their hash
codes,
> which I'm sure isn't right

Why not? After all Python uses dictionaries(hashes) for all of its
variables, and every object is an instance of a dictionary which
holds all the attributes... This is exactly the kind of thing hashes
are for.

As for using different initialisation parameters. Do you mean
different types of values or just different values?

If the former - like Java/C++ having multiple constructors - then the
best approach is to use named parameters - look at how Tkinter does
this as a good example.

class C:
 def __init__(self, a=None, b=None, c=None, d=None)
   # do stuff here

now provided you can think up some suitable default values you can
init your object with any combination of a,b,c and d you like like
this:

c1 = C(a="fred",d=42)
c2 = C(b=27,d=0)
c3 = C(a="joe", c=[1,2,3])

and so on...

I'm not sure if thats what you wanted but if not post again to
clarify...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list