If you want to create a class variable, you must to declare it outside any class methods (but still inside the class definition):
class Example(object):
somevariable = 'class variable'
With this you can now access your class variable.
>> Example.somevariable
'class variable'
The reason why your example isn't working is because you are assigning a value to an instance variable.
The difference between the two is that a class variable is created as soon as the class object is created. Whereas an instance variable will be created once the object has been instantiated and only after they have been assigned to.
class Example(object):
def doSomething(self):
self.othervariable = 'instance variable'
>> foo = Example()
Here we created an instance of Example, however if we try to access othervariable we will get an error:
>> foo.othervariable
AttributeError: 'Example' object has no attribute 'othervariable'
Since othervariable is assigned inside doSomething - and we haven't called ityet -, it does not exist.
>> foo.doSomething()
>> foo.othervariable
'instance variable'
__init__ is a special method that automatically gets invoked whenever class instantiation happens.
class Example(object):
def __init__(self):
self.othervariable = 'instance variable'
>> foo = Example()
>> foo.othervariable
'instance variable'
self.somevariableis an instance variable, not a class variable.exampleclass is an object, but it's of typetype, not of typeexample. Each instance of theexampleclass that you create with, e.g.,inst = example()is an object of typeexample. Your code creates asomevariableattribute in each object of typeexample.