"""
Case 1:
Here we have declared the result and some_string as static Class variable
"""
class Demo_1():
result = []
some_string = ""
def do_something(self):
Demo_1.some_string = Demo_1.some_string + "Python "
self.result.append(1)
self.result.append(2)
self.result.append(3)
return self.result
demo = Demo_1()
print Demo_1.result
result = demo.do_something()
print Demo_1.result
demo = Demo_1()
result = demo.do_something()
print Demo_1.result
demo = Demo_1()
result = demo.do_something()
print Demo_1.result
print result
print demo.some_string
print "Demo_1 class attributes :-", dir(Demo_1)
"""
Case1 Output :
[]
[1, 2, 3]
[1, 2, 3, 1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Python Python Python
Demo_1 class attributes :- ['__doc__', '__module__', 'do_something', 'result', 'some_string']
As you can see both result and some_string exists in Demo_1's attributes
which you can access by both by Class name as well as it's instance
"""
print "-----------------------------------------------------------------"
"""
Case 2:
Here we have declared the result variable as Class instance variable.
So each time we create an instance of class it creates new memory for that instance.
"""
class Demo_2():
def __init__(self):
self.result = []
self.some_string = " "
def do_something(self):
self.result.append(1)
self.result.append(2)
self.result.append(3)
return self.result
demo = Demo_2()
result = demo.do_something()
print demo.result
demo = Demo_2()
result = demo.do_something()
print demo.result
demo = Demo_2()
result = demo.do_something()
print demo.result
print result
print "Demo_1 class attributes :-", dir(Demo_2)
print Demo_2.some_string
"""
Case2 Output :
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
Demo_1 class attributes :- ['__doc__', '__init__', '__module__', 'do_something']
Traceback (most recent call last):
File "bl.py", line 83, in <module>
print Demo_2.some_string
AttributeError: class Demo_2 has no attribute 'some_string'
As you can see Class Demo_2 has no attributes result or some_string as
they are instance variable.
"""
See more about static Class variable Here