
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Class or Static Variables in Python?
In this article we are going to learn about class or static variables on python. The class variables or static variables that are used to share across all the instances of a class. Unlike the instance variables which are specific to each object, Class variables maintain the common value for all the objects of the class.
They are defined within the class but outside any instance methods, making them accessible to all the instances. These variables are used when we want to have a single shared state or value among all instance.
Example 1
Let's look at the following example, where we are going to demonstrate how class variable can be used to count the objects created.
class demo: count = 0 def __init__(self, name): self.name = name demo.count += 1 x1 = demo("Ravi") x2 = demo("Suresh") print("Result :", demo.count)
Following is the output of the above program -
Result : 2
Example 2
Consider the following example, where we are going to illustrate how class variable provides a shared configuration value across different objects.
class demo: studying = "B.tech" def __init__(self, user): self.user = user x1 = demo("Sunil") x2 = demo("Poorna") print(x1.studying) print(x2.studying)
The output of the above program is -
B.tech B.tech
Example 3
In the following example, we are going to modify the class variables from outside the class.
class demo: drive = "2stroke" def __init__(self, model): self.model = model print("Initial drive:", demo.drive) demo.drive = "4stroke" x1 = demo("Ciaz") print("After Modification :", x1.drive)
Following is the output of the above program -
Initial drive: 2stroke After Modification : 4stroke