Nearby lessons

104 of 159

Python - Static Variables

📌 What You Will Learn
  • Understand what a static variable is and how it is shared
  • Know the six places where static variables can be declared
  • Access static variables using the class name or an object reference
  • Modify and delete static variables
  • Distinguish between static variables and instance variables

Static Variables

Static variables are variables whose values are common to all objects of a class.

Unlike instance variables, static variables are created only once and are shared by every object.

A static variable belongs to the class, not to individual objects. Because there is only one copy, any modification is visible to all objects.

Static variables are also known as Class Variables.

Characteristics of Static Variables

  • Belong to the class rather than individual objects.
  • Only one copy exists in memory.
  • Shared among all objects of the class.
  • Every object accesses the same value.
  • Memory efficient because duplicate copies are not created.
  • Can be accessed using either the class name or an object reference.
  • Changing the value affects all objects.

Syntax

Static variables are declared directly inside the class but outside any method.

🐍Code Cell
1class Student:
2 
3 school = "ABC School"
4 
5 def __init__(self, name):
6 self.name = name
Output
No output captured.

Explanation

Here, school is a static (class) variable shared by every student, while name is an instance variable that is different for every student.

Instance Variable vs Static Variable

Feature Instance Variable Static Variable
Belongs To Object Class
Copies Created One per object Only one
Memory Usage Higher Lower
Values Can differ for each object Same for all objects
Access Using Object Reference Class Name or Object
Modification Effect Only that object All objects

Various Places to Declare Static Variables

Static variables can be declared or modified in several places within a Python program:

  1. Inside the Class (Direct Declaration)
  2. Inside the Constructor
  3. Inside an Instance Method
  4. Inside a Class Method
  5. Inside a Static Method
  6. Outside the Class

Each technique updates the class variable, which is shared by every object.

Program: Declaring Static Variables in All Six Places

🐍Code Cell
1class Student:
2 college = "ABC College"
3 
4 def __init__(self):
5 Student.city = "Ahmedabad"
6 
7 def setData(self):
8 Student.country = "India"
9 
10 @classmethod
11 def setCollege(cls):
12 cls.college = "XYZ College"
13 
14 @staticmethod
15 def setState():
16 Student.state = "Gujarat"
17 
18 
19s = Student()
20s.setData()
21Student.setCollege()
22Student.setState()
23Student.university = "GTU"
24 
25print("college :", Student.college)
26print("city :", Student.city)
27print("country :", Student.country)
28print("state :", Student.state)
29print("university:", Student.university)
Output
college   : XYZ College
city      : Ahmedabad
country   : India
state     : Gujarat
university: GTU

Explanation

  • college is declared directly inside the class and then updated inside the class method.
  • city is declared inside the constructor.
  • country is declared inside an instance method.
  • state is declared inside a static method.
  • university is declared outside the class using Student.university = "GTU".

Accessing Static Variables

Since static variables belong to the class, they can be accessed in two ways.

🐍Code Cell
1class Student:
2 
3 college = "ABC College"
4 
5 def __init__(self, name):
6 self.name = name
7 
8 
9s1 = Student("Raj")
10 
11print(Student.college)
12print(s1.college)
Output
ABC College
ABC College

Explanation

Although both approaches work, using the class name (Student.college) is considered the best practice because it clearly indicates that the variable belongs to the class.

Modifying Static Variables

Static variables should normally be modified using the class name.

🐍Code Cell
1class Student:
2 
3 college = "ABC College"
4 
5 
6print("Before:", Student.college)
7 
8Student.college = "XYZ College"
9 
10print("After :", Student.college)
Output
Before: ABC College
After : XYZ College

Deleting Static Variables

Static variables can be deleted using the del keyword.

🐍Code Cell
1class Student:
2 
3 college = "ABC College"
4 
5 
6del Student.college
7 
8print(Student.college)
Output
AttributeError: type object 'Student' has no attribute 'college'

Program: Banking Application Using a Static Variable

This program shows a real-world use of static and instance variables together.

🐍Code Cell
1class Customer:
2 
3 bankName = "State Bank of India"
4 
5 def __init__(self, name, balance=0):
6 self.name = name
7 self.balance = balance
8 
9 def deposit(self, amount):
10 self.balance += amount
11 print(amount, "Deposited Successfully")
12 
13 def withdraw(self, amount):
14 if amount > self.balance:
15 print("Insufficient Balance")
16 else:
17 self.balance -= amount
18 print(amount, "Withdrawn Successfully")
19 
20 def display(self):
21 print("-----------------------------")
22 print("Customer Name :", self.name)
23 print("Bank Name :", Customer.bankName)
24 print("Balance :", self.balance)
25 print("-----------------------------")
26 
27 
28c1 = Customer("Raj", 5000)
29c1.display()
30c1.deposit(2000)
31c1.withdraw(1500)
32c1.display()
33 
34c2 = Customer("Amit", 3000)
35c2.display()
36c2.withdraw(5000)
37c2.deposit(1000)
38c2.display()
Output
-----------------------------
Customer Name : Raj
Bank Name     : State Bank of India
Balance       : 5000
-----------------------------
2000 Deposited Successfully
1500 Withdrawn Successfully
-----------------------------
Customer Name : Raj
Bank Name     : State Bank of India
Balance       : 5500
-----------------------------
-----------------------------
Customer Name : Amit
Bank Name     : State Bank of India
Balance       : 3000
-----------------------------
Insufficient Balance
1000 Deposited Successfully
-----------------------------
Customer Name : Amit
Bank Name     : State Bank of India
Balance       : 4000
-----------------------------

Explanation

The static variable bankName is shared by every customer, so every display() call prints the same bank name.

The instance variables name and balance are different for every customer.

Notice that when withdraw() is called with an amount greater than the balance, the program displays "Insufficient Balance".

📝 Key Takeaways
  • A static variable belongs to the class and is shared by all objects
  • Only one copy of a static variable exists in memory
  • It is recommended to access static variables using the class name
  • Modifying a static variable affects every object of the class
  • Static variables can be declared inside the class, constructor, instance method, class method, static method, or outside the class

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8