one-time factory in python for an experienced java guy
Peter Otten
__peter__ at web.de
Tue Jul 14 11:20:03 EDT 2009
phonky wrote:
> Thanks Paul,
>
>> Ugh, just forget everything you ever knew about java. Do some Zen
>> exercises to erase your mind. Then read a Python tutorial as if
>> you're starting from nothing.
>
> Yeah, surely right, but easier said than done...
> I'm working on it.
>
> Taking your example.
>
> 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?
In that case you may want to stick with the class attribute:
>>> class Account(object):
... def __init__(self):
... self.account = self.next_account()
... def __str__(self):
... return "Account(number=%r)" % self.account
... __repr__ = __str__
...
>>> from itertools import count
>>> Account.next_account = count(42).next
>>> a = Account()
>>> b = Account()
>>> a, b
(Account(number=42), Account(number=43))
>>> from uuid import uuid1
>>> Account.next_account = staticmethod(uuid1)
>>> c = Account()
>>> d = Account()
>>> c, d
(Account(number=UUID('b0f8dfc6-7087-11de-be16-001d923f29c5')),
Account(number=UUID('b310c90e-7087-11de-be16-001d923f29c5')))
You can plug in arbitrary callables at runtime. The only complication I can
see is that you may have to wrap them into a staticmethod to prevent python
from passing the self reference. You can avoid that if you just use a global
instead:
# account.py
next_account = ...
class Account(object):
def __init__(self): self.number = next_account()
You can then set the factory elsewhere
# main.py
import account
account.next_account = ...
a = Account()
In general in python we like to keep simple things simple rather than
creating a huge bureaucracy.
Peter
More information about the Python-list
mailing list