Instance vs Class Variables
Demonstrate the difference between instance variables and class variables.
BeginnerTopic: Object-Oriented Programs
Python Instance vs Class Variables Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to demonstrate instance vs class variables
class Counter:
count = 0 # class variable
def __init__(self):
Counter.count += 1
self.id = Counter.count # instance variable
c1 = Counter()
c2 = Counter()
print("c1.id:", c1.id)
print("c2.id:", c2.id)
print("Total objects created:", Counter.count)Output
c1.id: 1 c2.id: 2 Total objects created: 2
Understanding Instance vs Class Variables
The class variable 'count' is shared across all instances, while 'id' is unique per instance.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.