[Tutor] Ok, take one step back and let you look
Michael P. Reilly
arcege@shore.net
Thu, 30 Sep 1999 15:40:03 -0400 (EDT)
> Just a little frustrated here, because I can't seem to make the
> connection on this little project: a basic inventory tracking system.
> Maybe a little too much, but hey, it's rather fun. Here's my
> problem: how do I make x number of objects (that is x number of
> different object instances, not x number of the same object
> instance) appear once in the inventory, with x number of items? I
> can do it with a single instance, amke it appear multiple times, but
> when I try it with different instances (but the same 'variables'), I
> can't seem to code it.
> Please could someone give me a suggestion? Not a solution,
> please. maybe a hint on what I need to do. Please teach me, don't
> lead me.
> Anyway, included is a copy of my code so you can laugh. yes I
> probably mangled all the technical terms, oh well, someday I'll get
> the straight.
It sounds like you want some form of "semaphore" when creating class
instances: a certain number of instances of that class can be
created, but beyond that the semaphore "blocks" (raises an exception
in this case). Here is a mix-in you can look at and see how to work
into your code.
class InstanceLimiter:
class InstanceLimiterError(Exception):
pass
_Instance_Limiter_count = 10
def new_instance(self):
klass = self.__class__
if klass._Instance_Limiter_count > 0:
klass._Instance_Limiter_count = klass._Instance_Limiter_count - 1
else:
raise self.InstanceLimiterError, \
'too many instances of %s' % klass.__name__
def remove_instance(self):
klass = self.__class__
klass._Instance_Limiter_count = klass._Instance_Limiter_count + 1
Then you can work it into a class like:
class Person(InstanceLimiter):
"""A person under population control."""
_Instance_Limiter_count = 1000
def __init__(self, name, location, birthdate):
self.new_instance()
...
def __del__(self):
self.remove_instance()
...
Now only one thousand instances of Person can exist.
I'm not sure if this is what you want, if not maybe you can use the
techniques in other places.
-Arcege
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------