Python class variables are shared by all python class instances. In this tutorial, we will write some examples to illustrate how to use python class variables for python beginners.
What are python variables?
Python variables are created outside of all python class methods, all of them are shared by all instances of this class.
How to create a python class variable?
To create a python class variable, we should create it outside of all python class methods. Here is an example:
class Test: count = 0 def __init__(self): print("init a class variable") def add(self): Test.count += 1 print("class variable count is = " + str(Test.count))
In this example, we have created a python class variable count in class Test, which means this variable is shared by all instances of class Test.
How to use a python class variable？
We can use python class variable by this way:
class_name.class_variable_name or cls.class_variable_name
Look at code above, we can find Test class varialbe count is called in add() method by:
However, you also can use like this:
While we recommend you to use Test.count.
How to understand all python class instances share class variables?
To understand it, we will use an example to explain.
t1 = Test() t1.add() t2 = Test() t2.add()
In code above, we have created two Test instances t1 and t2. Both of them can modify the python class variable count.
As to t1, when it call add(), which will make count to 1.
As to t2, it also will add 1 to count, however, t1 has added. If you use t2.add(), count will be 2.
Run this code, you will get result:
init a class variable class variable count is = 1 init a class variable class variable count is = 2
From the result we can find Test class variable count is shared by t1 and t2.