Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>class a: def __init__(self): self.val=1 </code></pre> <p>this creates a class (in Py2, a cruddy, legacy, old-style, <strong>don't do that!</strong> class; in Py3, the nasty old legacy classes have finally gone away so this would be a class of the one and only kind -- the **good* kind, which requires <code>class a(object):</code> in Py2) such that each instance starts out with its own reference to the integer object <code>1</code>.</p> <pre><code>class a: val=1 def __init__(self): pass </code></pre> <p>this creates a class (of the same kind) which itself has a reference to the integer object <code>1</code> (its instances start out with no per-instance reference).</p> <p>For immutables like <code>int</code> values, it's hard to see a practical difference. For example, in either case, if you later do <code>self.val = 2</code> on one instance of <code>a</code>, this will make an <em>instance</em> reference (the existing answer is badly wrong in this respect).</p> <p>The distinction is important for <em>mutable</em> objects, because they have mutator methods, so it's pretty crucial to know if a certain list is unique per-instance or shared among all instances. But for <em>immutable</em> objects, since you can never change the object itself but only assign (e.g. to <code>self.val</code>, which will always make a per-instance reference), it's pretty minor.</p> <p>Just about the only relevant difference for immutables: if you later assign <code>a.val = 3</code>, in the first case this will affect what's seen as <code>self.val</code> by each instance (except for instances that had their own <code>self.val</code> <em>assigned</em> to, or equivalent actions); in the second case, it will not affect what's seen as <code>self.val</code> by any instance (except for instances for which you had performed <code>del self.val</code> or equivalent actions).</p>
 

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