Which is more pythonic?
Travis Jensen
travis.jensen at gmail.com
Fri Jan 25 00:54:58 EST 2008
Well, regardless of being "pythonic" or not, the first is far more
understandable and therefore more maintainable. Objects were invented
to handle holding state; using a function to hold state is, in my
opinion, doing a language-based cheat. :)
tj
On Jan 24, 2008, at 10:14 PM, benjamin.zimmerman at gmail.com wrote:
> I have a goal function that returns the fitness of a given solution. I
> need to wrap that function with a class or a function to keep track of
> the best solution I encounter. Which of the following would best serve
> my purpose and be the most pythonic?
>
> class Goal:
> def __init__(self, goal):
> self.goal = goal
> self.best = None
> self.best_score = None
>
> def __call__(self, solution):
> score = self.goal(solution)
> if self.best is None or score > self.best_score:
> self.best_score = score
> self.best = solution
> return score
>
> def save_best_goal(goal):
> def new_goal(solution):
> score = goal(solution)
> if new_goal.best is None or score > new_goal.best_score:
> new_goal.best = solution
> new_goal.best_score = score
> return score
> new_goal.best = new_goal.best_score = None
> return new_goal
>
> -Ben
> --
> http://mail.python.org/mailman/listinfo/python-list
Travis Jensen
travis.jensen at gmail.com
http://softwaremaven.innerbrane.com/
You should read my blog; it is more interesting than my signature.
More information about the Python-list
mailing list