Skip to content
Related Articles
Open in App
Not now

Related Articles

Class or Static Variables in Python

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 22 Dec, 2022
Improve Article
Save Article

All objects share class or static variables. An instance or non-static variables are different for different objects (every object has a copy). For example, let a Computer Science Student be represented by a class CSStudent. The class may have a static variable whose value is “cse” for all objects. And class may also have non-static members like name and roll.

 In C++ and Java, we can use static keywords to make a variable a class variable. The variables which don’t have a preceding static keyword are instance variables. See this for the Java example and this for the C++ example.

Features of Static Variables

  • Static variables are allocated memory once when the object for the class is created for the first time.
  • Static variables are created outside of methods but inside a class
  • Static variables can be accessed through a class but not directly with an instance.
  • Static variables behavior doesn’t change for every object.

The Python approach is simple; it doesn’t require a static keyword. 

Note: All variables which are assigned a value in the class declaration are class variables. And variables that are assigned values inside methods are instance variables.



# Python program to show that the variables with a value
# assigned in class declaration, are class variables
# Class for Computer Science Student
class CSStudent:
    stream = 'cse'                  # Class Variable
    def __init__(self,name,roll): = name            # Instance Variable
        self.roll = roll            # Instance Variable
# Objects of CSStudent class
a = CSStudent('Geek', 1)
b = CSStudent('Nerd', 2)
print(  # prints "cse"
print(  # prints "cse"
print(    # prints "Geek"
print(    # prints "Nerd"
print(a.roll)    # prints "1"
print(b.roll)    # prints "2"
# Class variables can be accessed using class
# name also
print( # prints "cse"
# Now if we change the stream for just a it won't be changed for b = 'ece'
print( # prints 'ece'
print( # prints 'cse'
# To change the stream for all instances of the class we can change it
# directly from the class = 'mech'
print( # prints 'ece'
print( # prints 'mech'



My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!