Which is more pythonic?

Paddy paddy3118 at googlemail.com
Fri Jan 25 02:51:52 EST 2008


On Jan 25, 5:14 am, "benjamin.zimmer... at gmail.com"
<benjamin.zimmer... 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

You could also wrap the best score logic as a decorator applied to a
function to save the best score as a function attribute. Whilst not
class based, Python isn't solely an OO language. but if you know that
extra capabilities are going to be needed you might favour the class
based solution.

- Paddy.



More information about the Python-list mailing list