Learning Sections show
Instance variables vs Class variables in Python
In Python, instance variables are variables that are bound to instances of a class, while class variables are variables that are bound to the class itself. Each instance of the class has its own copy of instance variables, while class variables are shared among all instances of the class.
Instance variables are defined within methods of a class using the self
keyword, while class variables are defined directly within the class body.
Example:
class Car:
# Class variable
wheels = 4
# Instance method to initialize instance variables
def __init__(self, color):
# Instance variable
self.color = color
# Create instances of the Car class
car1 = Car('red')
car2 = Car('blue')
# Access instance variables
print(car1.color) # Output: 'red'
print(car2.color) # Output: 'blue'
# Access class variable
print(Car.wheels) # Output: 4
Instance variables are specific to each instance of a class and are used to store unique data for each instance. Class variables, on the other hand, are shared among all instances of the class and are typically used to store data that is common to all instances.
Differences:
- Instance variables are specific to each instance of a class, while class variables are shared among all instances of the class.
- Instance variables are defined within methods of a class using the
self
keyword, while class variables are defined directly within the class body. - Each instance of a class has its own copy of instance variables, while class variables are shared by all instances of the class.
- Instance variables are used to store unique data for each instance, while class variables are typically used to store data that is common to all instances.