Module 4 Lesson 4: Instance Attributes vs. Methods
Differentiate between an object's state and its behavior. Learn how to define methods, use the self keyword for interaction, and update attributes dynamically.
Module 4 Lesson 4: Instance Attributes vs. Methods
We now know how to give our objects data (Attributes). But an object isn't just a container; it's a living part of your program that can do things. In this lesson, we’ll explore Methods—functions that belong to a specific object.
Lesson Overview
In this lesson, we will cover:
- Attributes: The "Nouns" (Data).
- Methods: The "Verbs" (Actions).
- The
selfin Methods: Accessing an object's data from its actions. - Updating State: How methods can change attributes over time.
1. Nouns vs. Verbs
If you were building a "Bank Account" in code:
- Attributes (Nouns):
account_number,balance,owner_name. - Methods (Verbs):
deposit(),withdraw(),check_balance().
2. Defining an Instance Method
Methods are defined inside a class just like normal functions, but with one difference: The first parameter must always be self.
class Dog:
def __init__(self, name):
self.name = name
# This is an instance method
def bark(self):
print(f"{self.name} says: Woof! Woof!")
my_dog = Dog("Buddy")
my_dog.bark() # Output: Buddy says: Woof! Woof!
Visualizing the Process
graph TD
Start[Input] --> Process[Processing]
Process --> Decision{Check}
Decision -->|Success| End[Complete]
Decision -->|Retry| Process
3. Modifying Attributes via Methods
The most powerful thing a method can do is change the object's data. This is how we simulate real-world changes.
class Car:
def __init__(self, brand, speed=0):
self.brand = brand
self.speed = speed
def accelerate(self, amount):
self.speed += amount
print(f"The {self.brand} is now going {self.speed} mph.")
my_car = Car("Tesla")
my_car.accelerate(20) # Speed becomes 20
my_car.accelerate(30) # Speed becomes 50
4. Why Use Methods instead of Changing Data Directly?
You could just write my_car.speed = 100. But using a method like accelerate() allows you to add Rules. For example:
- "A car cannot accelerate past 120 mph."
- "A car cannot accelerate if the engine is off."
By using methods, you ensure your objects follow the laws of your "digital world."
Practice Exercise: The Fitness Tracker
Create a file named fitness.py.
- Define a class
User. - In
__init__, setnameandsteps_taken(defaulting to 0). - Add a method
walk(steps)that adds to the total steps and prints:"[Name] walked [X] steps today!" - Add a method
reset_steps()that sets the steps back to 0. - Create a user object, walk twice, and then reset.
Quick Knowledge Check
- What is the first parameter of every instance method?
- How is a method different from a regular function?
- Can a method access the object’s attributes? If so, how?
- Give an example of a "rule" you might put inside a
withdraw()method for a bank account.
Key Takeaways
- Attributes store data (state); Methods define behavior.
- Methods use
selfto interact with the object's own attributes. - Methods can update attributes dynamically.
- Methods allow you to implement logic and rules for your data.
What’s Next?
We’ve seen that we can change attributes directly (my_car.speed = 500). But what if we want to hide some data so it can only be changed by our rules? In Lesson 5, we’ll learn about Encapsulation and Data Hiding!