Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Others have explained the technical differences. I'll try to explain why you might want to use class variables.</p> <p>If you're only instantiating the class once, then class variables effectively <em>are</em> instance variables. However, if you're making many copies, or want to share state among a few instances, then class variables are very handy. For example:</p> <pre><code>class Foo(object): def __init__(self): self.bar = expensivefunction() myobjs = [Foo() for _ in range(1000000)] </code></pre> <p>will cause expensivefunction() to be called a million times. If it's going to return the same value each time, say fetching a configuration parameter from a database, then you should consider moving it into the class definition so that it's only called once and then shared across all instances.</p> <p>I also use class variables a lot when memoizing results. Example:</p> <pre><code>class Foo(object): bazcache = {} @classmethod def baz(cls, key): try: result = cls.bazcache[key] except KeyError: result = expensivefunction(key) cls.bazcache[key] = result return result </code></pre> <p>In this case, baz is a class method; its result doesn't depend on any instance variables. That means we can keep one copy of the results cache in the class variable, so that 1) you don't store the same results multiple times, and 2) each instance can benefit from results that were cached from other instances.</p> <p>To illustrate, suppose that you have a million instances, each operating on the results of a Google search. You'd probably much prefer that all those objects share those results than to have each one execute the search and wait for the answer.</p> <p>So I'd disagree with Lennart here. Class variables are <em>very</em> convenient in certain cases. When they're the right tool for the job, don't hesitate to use them.</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.
    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