0
0
Pythonprogramming~5 mins

Instance attributes in Python

Choose your learning style9 modes available
Introduction

Instance attributes store information unique to each object made from a class. They help keep data separate for each object.

When you want each object to have its own data, like a person's name or age.
When you create multiple objects from the same class but each needs different values.
When you want to change data for one object without affecting others.
When you want to keep track of details specific to one object, like a car's color or speed.
Syntax
Python
class ClassName:
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2

self refers to the current object being created.

Instance attributes are usually set inside the __init__ method.

Examples
This creates a Dog class where each dog has its own name and age.
Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
Each Car object will have its own color stored as an instance attribute.
Python
class Car:
    def __init__(self, color):
        self.color = color
Each Person object stores a different name.
Python
class Person:
    def __init__(self, name):
        self.name = name

p1 = Person('Alice')
p2 = Person('Bob')
print(p1.name)  # Alice
print(p2.name)  # Bob
Sample Program

This program creates two Book objects with different titles and authors. It prints each book's details using instance attributes.

Python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

book1 = Book('1984', 'George Orwell')
book2 = Book('Pride and Prejudice', 'Jane Austen')

print(f"Book 1: {book1.title} by {book1.author}")
print(f"Book 2: {book2.title} by {book2.author}")
OutputSuccess
Important Notes

You can add or change instance attributes anytime after creating the object.

Instance attributes belong to the object, not the class itself.

Summary

Instance attributes hold data unique to each object.

They are usually set inside the __init__ method using self.

Each object can have different values for its instance attributes.