On Nov 13, 11:32 am, "J. Cliff Dyer" <[EMAIL PROTECTED]> wrote: > On Thu, 2008-11-13 at 09:38 -0800, Matimus wrote: > > On Nov 13, 9:16 am, Joe Strout <[EMAIL PROTECTED]> wrote: > > > One thing I miss as I move from REALbasic to Python is the ability to > > > have static storage within a method -- i.e. storage that is persistent > > > between calls, but not visible outside the method. I frequently use > > > this for such things as caching, or for keeping track of how many > > > objects a factory function has created, and so on. > > > > Today it occurred to me to use a mutable object as the default value > > > of a parameter. A simple example: > > > > def spam(_count=[0]): > > > _count[0] += 1 > > > return "spam " * _count[0] > > > > >>> spam() > > > 'spam ' > > > >>> spam() > > > 'spam spam ' > > > Don't Do this, it is confusing and there are definitely (many) better > > facilities in python for handling saved state. > > > > Ooh, for a change I had another thought BEFORE hitting Send rather > > > than after. Here's another trick: > > > > def spam2(): > > > if not hasattr(spam2,'count'):spam2.count=0 > > > spam2.count += 1 > > > return "spam2 " * spam2.count > > > This is definitely preferred over the first. However the preferred > > method is just to use a class. Preserving state is what classes are > > for. > > Preserving state is what *objects* are for.
Not exclusively, generators also preserve state. def _spam(): count = 1 while 1: yield "spam " * count count += 1 spam = _spam.next() -- http://mail.python.org/mailman/listinfo/python-list