Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You should use the version that most clearly expresses what you are trying to achieve.</p> <p>In the example given, I'd say that object version is more clear, since it seems to be modeling an object with state that changes. Looking at the code that uses the value, the object version seems to express the clear intent, whereas the closure version seems to have operations (the indexing and 'magic' strings) that are beside the point.</p> <p>In Python, I would favor a closure based approach when what is needed is something that is mostly like a function, and perhaps needs to capture some state.</p> <pre><code>def tag_closure(singular, plural): def tag_it(n): if n == 1: return "1 " + singular else: return str(n) + " " + plural return tag_it t_apple = tag_closure("apple", "apples") t_cherry = tag_closure("cherry", "cherries"); print t_apple(1), "and", t_cherry(15) </code></pre> <p>This is perhaps a little clearer than the following:</p> <pre><code>class tag_object(object): def __init__(self, singular, plural): self.singular = singular self.plural = plural def tag(self, n): if n == 1: return "1 " + self.singular else: return str(n) + " " + self.plural t_apple = tag_object("apple", "apples") t_cherry = tag_object("cherry", "cherries"); print t_apple.tag(1), "and", t_cherry.tag(15) </code></pre> <p>As a rule of thumb: If the thing is really only a single function, and it is only capturing static state, then consider a closure. If the thing is intended to have mutable state, and/or has more than one function, use a class.</p> <p>Another way to put it: If you are creating a dict of closures, you are essentially duplicating the class machinery by hand. Better to leave it to the language construct designed to do it.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload