The Wayback Machine - https://web.archive.org/web/20241127035638/https://www.geeksforgeeks.org/g-fact-34-class-or-static-variables-in-python/
Open In App

Class or Static Variables in Python

Last Updated : 30 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Explanation:
In Python, a static variable is a variable that is shared among all instances of a class, rather than being unique to each instance. It is also sometimes referred to as a class variable because it belongs to the class itself rather than any particular instance of the class.

Static variables are defined inside the class definition, but outside of any method definitions. They are typically initialized with a value, just like an instance variable, but they can be accessed and modified through the class itself, rather than through an instance.

Features of Static Variables

  • Memory Efficiency: Static variables are allocated memory once when the object for the class is created for the first time.
  • Class Scope: Static variables are created outside methods but inside the class.
  • Access Through Class: Static variables can be accessed through the class but not directly through an instance.
  • Consistent Behavior: The behavior of static variables 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.

Example of Static Variables in Python

Python
# 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):
        self.name = name            # Instance Variable
        self.roll = roll            # Instance Variable

# Objects of CSStudent class
a = CSStudent('Geek', 1)
b = CSStudent('Nerd', 2)

print(a.stream)  # prints "cse"
print(b.stream)  # prints "cse"
print(a.name)    # prints "Geek"
print(b.name)    # prints "Nerd"
print(a.roll)    # prints "1"
print(b.roll)    # prints "2"

# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse"

# Now if we change the stream for just 'a', it won't be changed for 'b'
a.stream = 'ece'
print(a.stream) # prints 'ece'
print(b.stream) # prints 'cse'

# To change the stream for all instances of the class, we can change it 
# directly from the class
CSStudent.stream = 'mech'

print(a.stream) # prints 'ece'
print(b.stream) # prints 'mech'

Output
cse
cse
Geek
Nerd
1
2
cse
ece
cse
ece
mech

This example shows how class variables (or static variables) are shared across all instances. However, when an instance modifies the class variable, it creates its own copy, which leads to a different behavior.

Key Differences Between Class Variables in Python and Static Variables in Java/C++

While class variables in Python and static variables in Java/C++ serve a similar purpose of being shared across all instances, they behave differently when modified through an instance:

  • Java/C++ Behavior: When you modify a static variable in Java or C++, the change is reflected across all instances of the class, and they all remain synchronized with the static variable’s value.
  • Python Behavior: In Python, if you modify a class variable through an instance, a new instance variable is created. This separates the modified value from the original class variable, which remains unchanged for other instances.

Example to Demonstrate the Difference

Python
class MyClass:
    class_var = 'original'  # Class variable

# Creating two instances
obj1 = MyClass()
obj2 = MyClass()

# Changing class_var for obj1 only
obj1.class_var = 'modified'

# Outputs
print(obj1.class_var)  # Output: 'modified'
print(obj2.class_var)  # Output: 'original'
print(MyClass.class_var)  # Output: 'original'

Output
modified
original
original

Explanation: obj1 has created its own version of class_var, separating it from the class-level class_var. As a result, the class variable remains unchanged for other instances.

Instance Variables vs Class Variables in Python

  • Instance Variables: Variables that are unique to each object. They are created inside methods (typically __init__()).
  • Class Variables (Static Variables): Variables shared among all instances of a class. They are defined within the class, outside any methods.

Modified Example to Show Behavior

Python
class MyClass:
    static_var = 0  # Class variable

    def __init__(self):
        MyClass.static_var += 1  # Modify through class name
        self.instance_var = MyClass.static_var  # Instance variable

obj1 = MyClass()
print("obj1.instance_var:", obj1.instance_var)  # Output: 1

obj2 = MyClass()
print("obj2.instance_var:", obj2.instance_var)  # Output: 2

# Access class variable directly
print("MyClass.static_var:", MyClass.static_var)  # Output: 2

# Modify class variable using obj1 (this creates a new instance variable)
obj1.static_var = 10
print("obj1.static_var:", obj1.static_var)  # Output: 10 (instance variable now)
print("MyClass.static_var:", MyClass.static_var)  # Output: 2 (unchanged)
print("obj2.static_var:", obj2.static_var)  # Output: 2 (unchanged)

Output
obj1.instance_var: 1
obj2.instance_var: 2
MyClass.static_var: 2
obj1.static_var: 10
MyClass.static_var: 2
obj2.static_var: 2

Best Practices for Using Class Variables

  • Use Class Variables for Shared Data: If you want all instances to share a particular value or state, use class variables.
  • Modify Class Variables via Class Name: Always modify class variables using the class name (ClassName.variable) to avoid unintentionally creating an instance-level copy.
  • Avoid Modifying Class Variables from Instances: Modifying class variables through instances can lead to confusion, as it creates instance-level variables.
  • Be Careful in Multithreaded Environments: In multithreaded programs, unsynchronized class variables can cause race conditions.

Advantages:

  • Memory efficiency: Since static variables are shared among all instances of a class, they can save memory by avoiding the need to create multiple copies of the same data.
  • Shared state: Static variables can provide a way to maintain shared state across all instances of a class, allowing all instances to access and modify the same data.
  • Easy to access: Static variables can be accessed using the class name itself, without needing an instance of the class. This can make it more convenient to access and modify the data stored in a static variable.
  • Initialization: Static variables can be initialized when the class is defined, making it easy to ensure that the variable has a valid starting value.
  • Readability: Static variables can improve the readability of the code, as they clearly indicate that the data stored in the variable is shared among all instances of the class.

Disadvantages:

  • Inflexibility: Static variables can be inflexible, as their values are shared across all instances of the class, making it difficult to have different values for different instances.
  • Hidden dependencies: Static variables can create hidden dependencies between different parts of the code, making it difficult to understand and modify the code.
  • Thread safety: Static variables can be problematic in a multithreaded environment, as they can introduce race conditions and synchronization issues if not properly synchronized.
  • Namespace pollution: Static variables can add to the namespace of the class, potentially causing name conflicts and making it harder to maintain the code.
  • Testing: Static variables can make it more difficult to write effective unit tests, as the state of the static variable may affect the behavior of the class and its methods.

Overall, static variables can be a useful tool in Python programming, but they should be used with care and attention to potential downsides, such as inflexibility, hidden dependencies, and thread safety concerns.

Conclusion

Class variables, or static variables, in Python can be a powerful tool when used correctly. They allow you to share data across all instances of a class, but they need to be handled carefully to avoid hidden dependencies or unexpected behavior. Always remember to modify them through the class itself to prevent creating instance-specific variables unintentionally.

Class or Static Variables in Python – FAQs

What are Class Variables and Static Variables in Python?

In Python, class variables are variables that are shared among all instances of a class. They are not unique to each instance but are common and can be accessed by all instances of the class. They are defined within the class construction but outside any instance methods.

Static variables in Python are essentially the same as class variables. The term “static variable” is more commonly used in languages like C++ or Java, but in Python, this concept is typically referred to as a class variable.

What is the Difference Between Class and Static in Python?

The terms class and static are often used to describe variables and methods within a class:

  • Class Variables: Shared across all instances of the class.
  • Static Methods: Methods that belong to a class but don’t require a class instance to be called. They are marked with the @staticmethod decorator and can’t access or modify the class state. They are used when functionality is related to the class but does not require access to any instance-specific data.

What are Static Variables Between Classes?

Static variables between classes refer to variables that have the same value across different classes, not just instances of the same class. This is not a typical pattern directly supported by Python’s standard features; such shared variables would usually be defined in a separate module or superclass that different classes can access or inherit from.

What is an Example of a Static Variable in a Class?

Here’s an example showing how to define and use a static (class) variable in Python:

class Car:
    wheels = 4  # This is a class variable (static variable)

    def __init__(self, make, model):
        self.make = make  # These are instance variables
        self.model = model

# Access the class variable
print(Car.wheels)  # Outputs: 4

# Create instances of Car
car1 = Car("Toyota", "Corolla")
car2 = Car("Honda", "Accord")

# Access the same class variable through instances
print(car1.wheels)  # Outputs: 4
print(car2.wheels)  # Outputs: 4

# If we change the class variable using the class name
Car.wheels = 6

# It affects all instances
print(car1.wheels)  # Outputs: 6
print(car2.wheels)  # Outputs: 6

This example illustrates how class variables (static variables) are shared across all instances of a class, making them useful for attributes that should have a common state across instances.



Previous Article
Next Article

Similar Reads

Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Bound, unbound, and static methods in Python
Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can be Bound, Unbound or Static method. The static methods are one of the types of Unbound method. These types are explained in detail below. Bound methods If a function is an attr
5 min read
Python Plotly - Exporting to Static Images
In this article, we will discuss how to export plotly graphs as static images using Python. To get the job done there are certain additional installations that need to be done. Apart from plotly, orca and psutil have to be installed. psutil (python system and process utilities) is a cross-platform Python package that retrieves information about run
2 min read
Convert Audio to Video using Static Images in Python
In this article, we are going to convert an audio file(mp3) to a video file(mp4) using the images provided by the user to be shown during the duration of the video using Python. To do this, we will first convert the images to a GIF file and then combining with the audio file to produce the final video file. Packages Required Mutagen: This Python pa
5 min read
Python Pyramid - Static Assets
A lightweight web framework in Python that converts small web apps to large web apps is called Pyramid. There are various circumstances when the user needs to add some images, HTML code, CSS code, etc. along with the Python code in the web app. These are called static assets and can be added using the Pyramid in Python. Python Pyramid - Static Asse
5 min read
Type Systems:Dynamic Typing, Static Typing & Duck Typing
Dynamic Typing: In Dynamic Typing, type checking is performed at runtime. For example, Python is a dynamically typed language. It means that the type of a variable is allowed to change over its lifetime. Other dynamically typed languages are -Perl, Ruby, PHP, Javascript etc. Let's take a Python code example to see if a variable can change type: ##
3 min read
wxPython - Remove static text on clicking button
In this article we are going to learn about how can we remove static text from the frame on clicking a button present in the same frame. We need to follow some steps: Step 1: Create a static text in frame. Step 1: Create a button in the same frame. Step 1: Assign event function for the button. Step 4: Destroy static text using Destroy() function. S
1 min read
wxPython Static Box
In this article we are going to learn about Static Box in wxPython. A static box is a rectangle drawn around other windows to denote a logical grouping of items. Note that while the previous versions required that windows appearing inside a static box be created as its siblings (i.e. use the same parent as the static box itself), since wxWidgets 2.
2 min read
wxPython - Create Static Box using Create() method
In this article we are going to learn about Static Box in wxPython. A static box is a rectangle drawn around other windows to denote a logical grouping of items. In this article we will create Static Box using two step creation, in order to do that we will use Create() method. Syntax: wx.StaticBox.Create(parent, id=ID_ANY, label="", pos=DefaultPosi
2 min read
wxPython - Get visual attributes of static box
In this article we are going to learn how can we get wx.VisualAttributes associated with Static Box. In order to do that we will use static GetClassDefaultAttributes() function. GetClassDefaultAttributes() function is used to return wx.VisualAttributes object for properties like background colour, foreground colour and font. Syntax: wx.StaticBox.Ge
1 min read
Django Static File
Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virtual EnvironmentLet's understand how to add the Dja
3 min read
How to serve static files in Flask
Flask is a lightweight Web Server Gateway Interface or WSGI framework for web applications written in Python. It is designed to make web application development fast and easy and can scale to complex applications. This article describes and demonstrates how to serve various static files in Flask.  Serving Static Files in Flask Let's configure the v
5 min read
Why Django not Serve your Static Files in Debug False Mode
Django ships with a lightweight server called runserver that allows us to see live previews of our Django application. It promotes faster development, is great for development purposes, and is used during development not in production. DEBUG=True is a way to tell Django that we are currently in the development phase and the runserver can serve the
3 min read
Working with Static and Media Files in Django
Django's collectstatic management command is a powerful feature that helps manage static files by gathering them from various locations within a project and placing them into a single directory for deployment. This command is essential for preparing static files for production environments, ensuring that they are easily accessible and efficiently s
6 min read
Django Get the Static Files URL in View
In Django, static files such as CSS, JavaScript, and images are essential for building interactive and visually appealing web applications. While Django provides robust mechanisms to manage static files, we might need to access the URLs of these static files directly within our views, especially when we need to manipulate or dynamically generate co
3 min read
Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
3 min read
Python | Difference between Pandas.copy() and copying through variables
Pandas .copy() method is used to create a copy of a Pandas object. Variables are also used to generate copy of an object but variables are just pointer to an object and any change in new data will also change the previous data. The following examples will show the difference between copying through variables and Pandas.copy() method. Example #1: Co
2 min read
Inserting variables to database table using Python
In this article, we will see how one can insert the user data using variables. Here, we are using the sqlite module to work on a database but before that, we need to import that package. import sqlite3 To see the operation on a database level just download the SQLite browser database.Note: For the demonstration, we have used certain values but you
3 min read
How are variables stored in Python - Stack or Heap?
Memory allocation can be defined as allocating a block of space in the computer memory to a program. In Python memory allocation and deallocation method is automatic as the Python developers created a garbage collector for Python so that the user does not have to do manual garbage collection. Garbage Collection Garbage collection is a process in wh
3 min read
Python Scope of Variables
In Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. Python Scope variable The location where we can find a variable and al
5 min read
Tracing Tkinter variables in Python
There is no inbuilt way to track variables in Python. But tkinter supports creating variable wrappers that can be used to do so by attaching an 'observer' callback to the variable. The tkinter.Variable class has constructors like BooleanVar, DoubleVar, IntVarand StringVar for boolean, double-precision floating-point values, integer and strings resp
3 min read
How to Create Dummy Variables in Python with Pandas?
A dataset may contain various type of values, sometimes it consists of categorical values. So, in-order to use those categorical value for programming efficiently we create dummy variables. A dummy variable is a binary variable that indicates whether a separate categorical variable takes on a specific value. Explanation: As you can see three dummy
2 min read
Context Variables in Python
Context variable objects in Python is an interesting type of variable which returns the value of variable according to the context. It may have multiple values according to context in single thread or execution. The ContextVar class present in contextvars module, which is used to declare and work with context variables in python. Note: This is supp
4 min read
Environment Variables in Python
In Python, its behavior is highly influenced by the setup of the environment variables. There is a fixed number of environment variables that Python recognizes and these generally are processed before the command line switches. Whenever a conflict arises between the environmental variable and the command line switches, the environment variable gets
4 min read
Assigning multiple variables in one line in Python
A variable is a segment of memory with a unique name used to hold data that will later be processed. Although each programming language has a different mechanism for declaring variables, the name and the data that will be assigned to each variable are always the same. They are capable of storing values of data types. The assignment operator(=) assi
2 min read
Viewing all defined variables in Python
In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code. Method 1: Using dir() function dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all decl
5 min read
How to check multiple variables against a value in Python?
Given some variables, the task is to write a Python program to check multiple variables against a value. There are three possible known ways to achieve this in Python: Method #1: Using or operator This is pretty simple and straightforward. The following code snippets illustrate this method. Example 1: C/C++ Code # assigning variables a = 100 b = 0
2 min read
How to use Pickle to save and load Variables in Python?
Serialization is a technique used to save the state of an object from any process. We can later use this state by deserialization, to continue the process. Pickle is a python module that makes it easy to serialize or save variables and load them when needed. Unlike JSON serialization, Pickle converts the object into a binary string. JSON is text sp
2 min read
How to import variables from another file in Python?
When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simpl
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg