[OT] Re: general class functions
Steven Bethard
steven.bethard at gmail.com
Tue Nov 2 18:38:45 EST 2004
bruno modulix <onurb <at> xiludom.gro> writes:
>
> class Library:
> [...]
> def getAll(self, **kwargs):
> library=Library()
> for nation in self.list:
> keep = True
> for attribute, value in kwargs.items():
> if not getattr(nation, attribute) == value:
> keep = false
> break
> if keep :
> library.add(nation)
> return library
I haven't been watching this thread, but I saw a pattern here that Python allows
a much easier solution to. The code:
keep = True
for item in lst:
if test(item):
keep = False
break
if keep:
...
can generally be rewritten as:
for item in lst:
if test(item):
break
else:
For example:
>>> def loop1(lst, test):
... keep = True
... for item in lst:
... if test(item):
... keep = False
... break
... if keep:
... print "reached if"
...
>>> def loop2(lst, test):
... for item in lst:
... if test(item):
... break
... else:
... print "reached if"
...
>>> loop1(range(10), lambda x: x == 5)
>>> loop1(range(10), lambda x: x == 11)
reached if
>>> loop2(range(10), lambda x: x == 5)
>>> loop2(range(10), lambda x: x == 11)
reached if
Always good to take advantage of a language construct when you can. =)
Steve
More information about the Python-list
mailing list