one-time factory in python for an experienced java guy
Aahz
aahz at pythoncraft.com
Tue Jul 14 11:24:14 EDT 2009
In article <23406$4a5c9c7d$d9a2f023$27926 at news.hispeed.ch>,
phonky <phonky at europe.com> wrote:
>
>import itertools
>
> class Account(object):
> def __init__(self, holder, gen=itertools.count()):
> self.__accountnumber = gen.next()
>
>If you consider my python illiteracy,
>
>"itertools.count(): Make an iterator that returns consecutive integers
>starting with n"
>
>to me that sounds like that solves the increment issue, but what about
>future modules wanting to plug in a different
>numbering format, e.g. 205434.1234 or whatever?
Here's what I would do:
class Account:
gen = itertools.count
gen_instance = None
def __init__(self, holder):
if self.gen_instance is None:
self.__class__.gen_instance = self.gen()
self._account = self.gen_instance()
Notice that I'm using only a single underscore for ``_account`` to make
inheritance simpler, and I'm using ``self`` to access class attributes
*except* when I need to *set* the class attribute, which requires
``self.__class__``.
Now anyone who wants to change the generator can simply do
module.Account.gen = other_gen
and it will work as long as no Account() instances have been created (you
don't want the generator to change mid-stream, right?).
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur." --Red Adair
More information about the Python-list
mailing list