- Learning Objectives
- Prerequisites
- Introduction
- What are Variables in Python OOP?
- Types of Variables
- What is an Instance Variable?
- What is a Static Variable (Class Variable)?
- Why are Static Variables Required?
- Instance Variables vs Static Variables
- Namespace Concepts
- Accessing Static Variables
- Modifying Static Variables
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand Variables in OOP.
- Differentiate Instance Variables and Static Variables.
- Learn Class Variables.
- Understand Namespace Concepts.
- Learn how Python stores variables in memory.
- Access and modify Static Variables correctly.
Before learning this chapter, you should know:
- Classes
- Objects
- Methods
- Constructors
- Access Specifiers
When we create objects in Python,
every object stores its own data.
Sometimes,
certain data should be shared by every object.
For example,
consider a College.
Every Student has
- Name
- Roll Number
- Marks
These values differ for every student.
However,
the
College Name
College Address
University Name
remain the same for every student.
Instead of storing identical information inside every object,
Python stores it only once.
This is called a Static Variable or Class Variable.
Variables are used to store data.
In Object-Oriented Programming,
variables are mainly divided into two types.
- Instance Variables
- Static Variables (Class Variables)
Belong to an individual object.
Every object has its own copy.
Example
Student1
Name → Rahul
Age → 21
-------------------
Student2
Name → Priya
Age → 20
Each object stores different values.
Belong to the class.
Only one copy exists.
Every object shares that copy.
Example
College Name
↓
KodNest
Every Student object uses the same value.
An Instance Variable belongs to an object.
A separate copy is created for every object.
Instance Variables are declared using
selfExample
class Student:
def __init__(self):
self.name = "Rahul"A Static Variable is a variable that belongs to the class rather than individual objects.
Only one copy exists,
and every object shares it.
Static Variables are also called
- Class Variables
class Student:
college = "KodNest"Here,
collegeis a Static Variable.
Suppose there are
1000 Students
Should every object store
College Name
University Name
Country
1000 times?
No.
Only one copy is sufficient.
This reduces memory usage.
Employee
Instance Variables
Employee ID
Employee Name
Salary
Static Variables
Company Name
Company Address
CEO Name
Every employee belongs to the same company.
| Instance Variable | Static Variable |
|---|---|
| Belongs to Object | Belongs to Class |
| Separate Copy for Every Object | One Copy Shared by All Objects |
| Created during Object Creation | Created when the Class is Loaded |
| Accessed using Object | Accessed using Class or Object |
Uses self |
Declared inside Class Body |
Python maintains different namespaces.
Variables inside a function.
Variables declared outside functions and classes.
Contains
- Static Variables
- Class Methods
Contains
- Instance Variables
Every object has its own namespace.
Static Variables can be accessed using
Student.collegestudent.collegeAlthough both work,
using the Class Name is recommended because it clearly indicates that the variable belongs to the class.
Static Variables should normally be modified using the Class Name.
Example
Student.college = "OpenAI University"This updates the value for all objects.
Class Loaded
↓
Static Variables Created
↓
Object Created
↓
Instance Variables Created
↓
Object Accesses Static Variable
↓
Shared Copy Returned
Student Class
+------------------------+
college
↓
"KodNest"
+------------------------+
▲ ▲
│ │
Student1 Student2
│ │
name name
age age
- Saves memory.
- Reduces duplicate data.
- Easy to maintain.
- Shared among all objects.
- Faster access.
- Improves consistency.
- Shared modifications affect every object.
- Should not be used for object-specific data.
Static Variables are used in:
- Company Information
- College Information
- Bank Information
- Tax Rates
- Currency Symbols
- Application Configuration
- Database Connection Settings
In this part, you learned:
- Variables in OOP
- Instance Variables
- Static Variables
- Namespace Concepts
- Memory Representation
- Accessing Static Variables
- Modifying Static Variables
- Advantages
- Real-Time Applications
Write a Python program to create and access a Static Variable.
class Student:
college = "KodNest"
student1 = Student()
student2 = Student()
print(student1.college)
print(student2.college)KodNest
KodNest
college is a Static Variable.
Only one copy exists.
Both objects access the same variable.
Write a Python program to create Instance Variables.
class Student:
college = "KodNest"
def __init__(self, name):
self.name = name
student1 = Student("Rahul")
student2 = Student("Priya")
print(student1.name)
print(student2.name)Rahul
Priya
name is an Instance Variable.
Each object stores its own copy.
class Student:
college = "KodNest"
def __init__(self, name):
self.name = name
student1 = Student("Rahul")
student2 = Student("Priya")
print(student1.name, student1.college)
print(student2.name, student2.college)Rahul KodNest
Priya KodNest
Every object has its own
namebut both objects share
collegeclass Student:
college = "KodNest"
print(Student.college)KodNest
This is the recommended way to access Static Variables.
class Student:
college = "KodNest"
student1 = Student()
student2 = Student()
Student.college = "OpenAI University"
print(student1.college)
print(student2.college)
print(Student.college)OpenAI University
OpenAI University
OpenAI University
Changing the Static Variable using the class updates the shared value for all objects.
class Student:
college = "KodNest"
student1 = Student()
student2 = Student()
student1.college = "ABC College"
print(student1.college)
print(student2.college)
print(Student.college)ABC College
KodNest
KodNest
This is one of the most confusing interview questions.
When we write
student1.college = "ABC College"Python does not modify the Static Variable.
Instead,
Python creates a new Instance Variable named
collegeinside student1.
Now,
student1
↓
Instance Variable
↓
college = ABC College
while
Student Class
↓
Static Variable
↓
college = KodNest
and
student2
↓
Uses Static Variable
remain unchanged.
class Student:
college = "KodNest"
def __init__(self, name):
self.name = name
student = Student("Rahul")
print(Student.__dict__)
print(student.__dict__)Class Namespace
{
'college': 'KodNest'
...
}
Object Namespace
{
'name': 'Rahul'
}
__dict__ displays the namespace.
Class Namespace stores
- Static Variables
- Methods
Object Namespace stores
- Instance Variables
class Student:
count = 0
def __init__(self):
Student.count += 1
Student()
Student()
Student()
print(Student.count)3
Every time an object is created,
the Static Variable
countis incremented.
This is a common real-world use of Static Variables.
class Employee:
company = "OpenAI"
def __init__(self, name):
self.name = name
employee1 = Employee("Rahul")
employee2 = Employee("Priya")
print(employee1.company)
print(employee2.company)OpenAI
OpenAI
class Bank:
interest_rate = 7.5
customer1 = Bank()
customer2 = Bank()
print(customer1.interest_rate)
print(customer2.interest_rate)7.5
7.5
Interest rate is common to every customer.
Hence,
it is represented using a Static Variable.
Class Loaded
↓
Static Variable Created
↓
Object Created
↓
Instance Variable Created
↓
Object Searches
↓
Object Namespace
↓
If Not Found
↓
Class Namespace
↓
Value Returned
Student Object
↓
Search Object Namespace
↓
Found?
↓
Yes → Return Value
↓
No
↓
Search Class Namespace
↓
Return Static Variable
Student Class
+--------------------------------+
college
↓
KodNest
count
↓
2
+--------------------------------+
▲ ▲
│ │
Student1 Student2
│ │
name name
↓
Rahul Priya
- Saves memory.
- One shared copy.
- Easy maintenance.
- Suitable for common data.
- Improves consistency.
- Faster access.
- Declare Static Variables inside the class body.
- Access Static Variables using the Class Name.
- Use Static Variables only for common data.
- Do not store object-specific information in Static Variables.
- Modify Static Variables using the Class Name.
Changing Static Variables using an object.
student.college = "ABC"This creates an Instance Variable.
Using Static Variables for object-specific data.
Incorrect
company
salary
nameOnly
companyshould be static.
Confusing Class Namespace with Object Namespace.
Always remember
Class Namespace
↓
Static Variables
Object Namespace
↓
Instance Variables
A Static Variable is a variable that belongs to the class and is shared by all objects.
Class Variable.
Inside the Class Namespace.
Inside the Object Namespace.
Only one copy.
One copy per object.
Python creates a new Instance Variable instead of modifying the Class Variable.
Using the Class Name.
__dict__
- Company Name
- College Name
- Bank Name
- Interest Rate
- GST Percentage
- Currency Symbol
- Create a Student class with a Static Variable.
- Count objects using a Static Variable.
- Demonstrate Class Namespace and Object Namespace.
- Modify a Static Variable using the Class Name.
- Show the difference between Instance Variables and Static Variables.
- Static Variable = Class Variable.
- One copy per class.
- Shared among all objects.
- Declared inside the class body.
- Stored in the Class Namespace.
- Access using the Class Name.
- Instance Variables belong to objects.
__dict__displays namespaces.
In this chapter, we learned:
- Static Variables
- Instance Variables
- Class Variables
- Namespace Concepts
- Accessing Static Variables
- Modifying Static Variables
- Class Namespace
- Object Namespace
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision