Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to create a class variable, you must to declare it outside any class methods (but still inside the class definition):</p> <pre><code>class Example(object): somevariable = 'class variable' </code></pre> <p>With this you can now access your class variable.</p> <pre><code>&gt;&gt; Example.somevariable 'class variable' </code></pre> <hr> <p>The reason why your example isn't working is because you are assigning a value to an <code>instance</code> variable. </p> <p>The difference between the two is that a <code>class</code> variable is created as soon as the class object is created. Whereas an <code>instance</code> variable will be created once the object has been <em>instantiated</em> and only after they have been assigned to. </p> <pre><code>class Example(object): def doSomething(self): self.othervariable = 'instance variable' &gt;&gt; foo = Example() </code></pre> <p>Here we created an instance of <code>Example</code>, however if we try to access <code>othervariable</code> we will get an error:</p> <pre><code>&gt;&gt; foo.othervariable AttributeError: 'Example' object has no attribute 'othervariable' </code></pre> <p>Since <code>othervariable</code> is assigned inside <code>doSomething</code> - and we haven't called ityet -, it does not exist.</p> <pre><code>&gt;&gt; foo.doSomething() &gt;&gt; foo.othervariable 'instance variable' </code></pre> <hr> <p><code>__init__</code> is a special method that automatically gets invoked whenever class instantiation happens. </p> <pre><code>class Example(object): def __init__(self): self.othervariable = 'instance variable' &gt;&gt; foo = Example() &gt;&gt; foo.othervariable 'instance variable' </code></pre>
 

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