If you want to create a class variable, you must declare it outside of 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 your example does not work is because you are assigning a value to the instance variable.
The difference between the two is that when you create the class object, the class variable is created. While the instance variable will be created after creating the instance of the object and only after they have been assigned.
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 get an error message:
>> foo.othervariable AttributeError: 'Example' object has no attribute 'othervariable'
Since othervariable is assigned inside doSomething - and we did not call ityet - it does not exist.
>> foo.doSomething() >> foo.othervariable 'instance variable'
__init__ is a special method that is automatically called whenever a class instance occurs.
class Example(object): def __init__(self): self.othervariable = 'instance variable' >> foo = Example() >> foo.othervariable 'instance variable'
source share