Welcome to our comprehensive guide on Instance Attributes in Python! This lesson is designed for both beginners and intermediates. By the end of this tutorial, you'll have a solid understanding of instance attributes, their importance, and how to use them effectively. Let's dive in!
Instance attributes, also known as instance variables, are attributes that belong to a specific instance of a class. Each instance can have its own set of instance attributes, which can be modified without affecting other instances of the same class.
class Car:
def __init__(self, brand, model, color):
self.brand = brand # Instance Attribute
self.model = model
self.color = color
def display_info(self):
print(f'Brand: {self.brand}')
print(f'Model: {self.model}')
print(f'Color: {self.color}')
# Creating an instance
my_car = Car('Toyota', 'Corolla', 'Blue')
# Calling the method
my_car.display_info()In the above example, brand, model, and color are instance attributes. Each time you create a new instance, these attributes can have different values.
Instance attributes can be modified within the instance itself.
my_car.color = 'Red'
my_car.display_info()In this example, we changed the color of the car instance, and then printed the updated information.
You can also provide default values for instance attributes using the __init__ method.
class Car:
def __init__(self, brand='Toyota', model='Corolla', color='Blue'):
self.brand = brand
self.model = model
self.color = color
def display_info(self):
print(f'Brand: {self.brand}')
print(f'Model: {self.model}')
print(f'Color: {self.color}')
# Creating an instance without providing values for brand, model, and color
my_car = Car()
# Calling the method
my_car.display_info()In this example, we provided default values for the instance attributes. If no values are provided while creating an instance, these default values will be used.
What are Instance Attributes in Python?
That's it for this lesson on Instance Attributes in Python! In the next lesson, we'll delve into more advanced topics. Stay tuned! 🎯