Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Classes & ObjectsMethods & SelfInstance VariablesClass VariablesConstructors & InitializationInheritance BasicsPolymorphismEncapsulationMagic Methods & Dunder
Python/Oop/Instance Variables

💾 Instance Variables — Object State and Data

Instance variables are attributes that belong to individual objects. Each object has its own copy of instance variables with potentially different values. Instance variables store the state and data specific to each object, making objects independent and unique.


🎯 What are Instance Variables?

Instance variables are variables defined with `self.variable_name` inside methods (usually in `__init__`). They store data unique to each object. Unlike class variables (which we'll learn about later), instance variables are not shared between objects—each object has its own values.

class Dog:
    def __init__(self, name, breed, age):
        self.name = name    # Instance variable
        self.breed = breed  # Instance variable
        self.age = age      # Instance variable

# Create objects with different values
dog1 = Dog("Buddy", "Golden Retriever", 3)
dog2 = Dog("Max", "Labrador", 5)

# Each object has its own instance variables
print(dog1.name)  # Output: Buddy
print(dog2.name)  # Output: Max

print(dog1.age)   # Output: 3
print(dog2.age)   # Output: 5

🔧 Creating Instance Variables

Instance variables are typically created in the `__init__` method, which is called automatically when an object is created. You can also add instance variables in other methods, but it's best practice to initialize them in `__init__` so all objects start with the same structure.

class Student:
    def __init__(self, student_id, name, grade):
        # Initialize instance variables
        self.student_id = student_id
        self.name = name
        self.grade = grade
        self.gpa = 4.0
        self.courses = []  # Can initialize as empty list
        self.enrolled = True

    def display_info(self):
        # Access instance variables
        return f"{self.name} (ID: {self.student_id}) - Grade: {self.grade}"

# Create student
student = Student(101, "Sarah", "A")
print(student.display_info())
print(f"GPA: {student.gpa}")
print(f"Courses: {student.courses}")

📊 Accessing and Modifying Instance Variables

You access instance variables using dot notation (object.variable). You can read their values or modify them. Any changes to an instance variable only affect that specific object.

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance
        self.transaction_count = 0

    def deposit(self, amount):
        self.balance += amount              # Modify instance variable
        self.transaction_count += 1         # Modify another
        return f"Deposited ${amount}"

    def get_details(self):
        return f"Owner: {self.owner}, Balance: ${self.balance}, Transactions: {self.transaction_count}"

# Create accounts
account1 = BankAccount("Alice", 1000)
account2 = BankAccount("Bob", 500)

# Modify each independently
print(account1.deposit(200))
print(account2.deposit(100))

print(account1.get_details())
# Output: Owner: Alice, Balance: $1200, Transactions: 1

print(account2.get_details())
# Output: Owner: Bob, Balance: $600, Transactions: 1

🎁 Instance Variables vs Local Variables

Local variables exist only within a method and disappear when the method ends. Instance variables persist as long as the object exists. This is what makes instance variables useful—they maintain state across multiple method calls.

class Counter:
    def __init__(self):
        self.count = 0  # Instance variable - persists

    def increment(self):
        local_var = 1   # Local variable - gone after method
        self.count += local_var  # Use instance variable
        return self.count

counter = Counter()
print(counter.increment())  # Output: 1
print(counter.increment())  # Output: 2
print(counter.increment())  # Output: 3
# self.count persists, local_var is created and destroyed each time

💪 Complex Instance Variables

Instance variables can store any type of data—strings, numbers, lists, dictionaries, or even other objects. Complex types allow you to create rich, structured objects.

class Library:
    def __init__(self, name):
        self.name = name
        self.books = []           # List of books
        self.members = {}         # Dictionary of members
        self.total_visits = 0     # Number

    def add_book(self, title):
        self.books.append(title)

    def register_member(self, member_id, member_name):
        self.members[member_id] = member_name

    def record_visit(self):
        self.total_visits += 1

    def get_status(self):
        return f"{self.name}: {len(self.books)} books, {len(self.members)} members, {self.total_visits} visits"

library = Library("City Library")
library.add_book("1984")
library.add_book("Brave New World")
library.register_member(1, "Alice")
library.register_member(2, "Bob")
library.record_visit()
library.record_visit()

print(library.get_status())
# Output: City Library: 2 books, 2 members, 2 visits

🔄 Initializing Different Types

Instance variables can hold different data types. You can initialize them with values in `__init__` and modify them later through methods.

class UserProfile:
    def __init__(self, username):
        self.username = username
        self.email = ""                    # String
        self.age = 0                       # Integer
        self.followers = []                # List
        self.settings = {                  # Dictionary
            "notifications": True,
            "theme": "light"
        }
        self.premium = False               # Boolean

    def set_email(self, email):
        self.email = email

    def add_follower(self, follower):
        self.followers.append(follower)

    def change_theme(self, theme):
        self.settings["theme"] = theme

    def show_profile(self):
        return f"{self.username} ({self.email}) - {len(self.followers)} followers, Premium: {self.premium}"

user = UserProfile("alice_wonder")
user.set_email("alice@example.com")
user.add_follower("bob")
user.add_follower("charlie")
user.change_theme("dark")

print(user.show_profile())
# Output: alice_wonder (alice@example.com) - 2 followers, Premium: False

📚 Real-World Examples

Product Inventory

class Product:
    def __init__(self, product_id, name, price, quantity):
        self.product_id = product_id
        self.name = name
        self.price = price
        self.quantity = quantity
        self.reviews = []

    def add_review(self, rating, comment):
        self.reviews.append({"rating": rating, "comment": comment})

    def sell(self, amount):
        if amount <= self.quantity:
            self.quantity -= amount
            return f"Sold {amount} units"
        return "Not enough stock"

    def restock(self, amount):
        self.quantity += amount

    def get_info(self):
        avg_rating = sum(r["rating"] for r in self.reviews) / len(self.reviews) if self.reviews else 0
        return f"{self.name} (${self.price}) - {self.quantity} in stock, Rating: {avg_rating}"

product = Product(1, "Laptop", 999.99, 10)
product.add_review(5, "Excellent!")
product.add_review(4, "Good value")
product.sell(2)
print(product.get_info())

Game Character

class Character:
    def __init__(self, name, character_class, level):
        self.name = name
        self.character_class = character_class
        self.level = level
        self.health = 100
        self.mana = 50
        self.experience = 0
        self.equipment = []

    def take_damage(self, damage):
        self.health = max(0, self.health - damage)

    def heal(self, amount):
        self.health = min(100, self.health + amount)

    def gain_experience(self, amount):
        self.experience += amount

    def equip_item(self, item):
        self.equipment.append(item)

    def get_status(self):
        return f"{self.name} ({self.character_class}) - Level {self.level}, HP: {self.health}, XP: {self.experience}"

character = Character("Aragorn", "Ranger", 10)
character.take_damage(20)
character.gain_experience(100)
character.equip_item("Sword")
character.equip_item("Shield")
print(character.get_status())

✅ Key Takeaways

ConceptRemember
Instance VariableA variable that belongs to a specific object
Unique ValuesEach object has its own copy with independent values
self PrefixCreated using self.variable_name
PersistentPersist for the lifetime of the object
Any TypeCan store strings, numbers, lists, dicts, objects, etc.
InitializationUsually created in __init__ method
AccessUse dot notation: object.variable_name
ModificationCan be changed through methods or directly

🔗 What's Next?

Now let's learn about class variables, which are shared across all instances of a class.

Next: Class Variables →


Ready to practice? Try challenges or explore more concepts


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn