Instance Variables and Methods
Overview
Instance variables hold data unique to each object, while methods define its behaviors. This lesson explains how to use the self keyword to connect data to specific instances and make your code more dynamic, enabling object-specific functionality.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Instance variables: Understand what instance variables are and how they store unique data for each object.
- The self keyword: Learn how
selfconnects methods to specific object instances. - Instance methods: Discover how to define methods that work with object-specific data.
- Accessing variables: Learn how to access and modify instance variables from within methods.
Why This Matters
Instance variables are what make each object unique! While all objects from the same class share the same structure, instance variables store the specific data for each object. Methods use self to access and modify this object-specific data, allowing you to create dynamic, interactive objects that behave differently based on their individual data.
Step 1: Understanding Instance Variables
Instance variables are attributes that belong to a specific object instance. Each object has its own copy of these variables:
class Dog:
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
# Each dog has its own name and age
print(dog1.name) # "Buddy"
print(dog2.name) # "Max"
Define in __init__
Instance variables are typically created in the __init__ method using self.variable_name. This assigns values that are unique to each object.
Each Object Has Its Own
When you create multiple objects from the same class, each object gets its own independent copy of all instance variables. Changing one object's variables doesn't affect others!
Access with Dot Notation
You access instance variables using object.variable_name. This gets the value stored in that specific object.
Key Concept: Instance variables are like personal belongings - each person (object) has their own items (variables). Two people might both have a wallet (instance variable), but they contain different things (different values)!
Mini Practice #1: Instance Variables
Try It YourselfCreate objects with instance variables:
What happened? Each Student object has its own name and grade instance variables. student1.name is "Alice" and student2.name is "Bob" - they're completely independent! Instance variables store data that's unique to each specific object.
Step 2: The self Keyword
self is a special parameter that refers to the current object instance. It's how methods access and modify instance variables:
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # self refers to this object
self.balance = balance # self.balance = this object's balance
def deposit(self, amount):
self.balance += amount # Modify this object's balance
def get_balance(self):
return self.balance # Return this object's balance
First Parameter
Every instance method must have self as its first parameter. Python automatically passes the object instance when you call the method.
Access Instance Variables
Use self.variable_name to access or modify instance variables from within methods. This ensures you're working with the correct object's data.
Don't Pass self
When calling methods, you don't pass self - Python does that automatically! Just call object.method().
Why self?
The name self is a convention - it could be anything, but everyone uses self so your code is readable. It means "this specific object I'm working with right now". When you call account1.deposit(100), Python automatically passes account1 as self!
Step 3: Instance Methods
Instance methods are functions defined inside a class that work with instance variables. They always take self as the first parameter:
class Car:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
def accelerate(self):
self.speed += 10
def brake(self):
self.speed -= 5
def get_info(self):
return f"{self.brand} is going {self.speed} mph"
car1 = Car("Toyota", 50)
car1.accelerate()
print(car1.get_info()) # "Toyota is going 60 mph"
Define Methods
Methods are defined using def inside the class. They always start with self as the first parameter.
Modify Instance Variables
Methods can read and modify instance variables using self. This allows methods to change the object's state based on its own data.
Call Methods
Call methods on objects using object.method(). The method automatically receives the object as self.
Mini Practice #2: Instance Methods
Try It YourselfCreate methods that work with instance variables:
What happened? The get_area() method calculates the area using the rectangle's instance variables. The double_size() method modifies the instance variables, changing the rectangle's size. Both methods use self to access the object's specific data!
Step 4: Multiple Methods Working Together
Instance methods can call other instance methods using self:
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def increment_by(self, amount):
self.count += amount
def reset(self):
self.count = 0
def display(self):
return f"Count is {self.count}"
counter = Counter()
counter.increment()
counter.increment_by(5)
print(counter.display()) # "Count is 6"
Remember: All instance methods share access to the same instance variables through self. This allows methods to work together, each modifying or reading the object's state as needed!
End-of-Lesson Exercises
Exercise 1: Create Instance Variables
Create a Book class with instance variables title and author. Create a Book object with title "Python Guide" and author "Jane Smith", then print both values.
Define class Book, add __init__ with self.title and self.author, create object, print attributes.
Exercise 2: Instance Methods
Create a BankAccount class with instance variable balance (set to 0 in __init__). Add a method deposit(self, amount) that adds to balance, and a method get_balance(self) that returns the balance. Create an account, deposit 100, and print the balance.
Define class BankAccount, add __init__ with self.balance = 0, add deposit and get_balance methods, create object, deposit, print balance.