Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 17

Object Methods: Actions and Interactions

Recommended resources

Hello! Welcome to the fourth lesson in our module on Object-Oriented Programming.

In our last lesson, we took a big step forward by implementing the __init__ constructor. This allowed us to create objects with their own unique data, or attributes, like a Car with a specific color and mileage. So far, our objects are like containers for data.

Today, we're going to bring them to life. Your goal is to learn how to define and call methods on an object to perform actions. Methods are functions that belong to a class, and they give our objects behavior, allowing them to act on their own data.


1. From Data to Behavior: What is a Method?

If attributes are the nouns that describe an object (like name, age, color), then methods are the verbs that describe what an object can do (like bark(), drive(), calculate_email()).

A method is simply a function that is defined inside a class. Because it's part of the class, it can access and use the object's instance attributes.

Let's continue with the Employee class example from the previous lesson's videos. The Employee objects have first, last, and pay attributes. A useful action would be to get the employee's full name. We can create a method for that.

Python OOP Tutorial 1: Classes and Instances

This clip from Corey Schafer's 'Python OOP Tutorial 1' introduces the concept of methods and shows how to define one.

Watch from 08:43 to 10:38. Pay close attention to these points: Definition: A method is defined just like a function, using def, but inside the class. The self Parameter: Notice that the full_name method takes self as its first argument. This is how the method gets access to the specific instance it's being called on. Accessing Attributes: Inside the method, self.first and self.last are used to access the data of that particular employee instance.

As you saw, defining a method is straightforward. Here's a textual summary to reinforce the concept, using a Dog class as an example.

Object-Oriented Programming (OOP) in Python

The article 'Object-Oriented Programming (OOP) in Python' on Real Python provides a clear, written definition of instance methods.

Find the section titled 'Instance Methods'. Read the text and review the Dog class example. Notice how the description() and speak() methods are defined and how they use self.name and self.age.


2. Calling a Method

Once a method is defined in the class, you can "call" it on any instance of that class. The syntax is instance_name.method_name().

It's crucial to include the parentheses () at the end.

  • my_dog.name accesses the name attribute (data).
  • my_dog.speak() calls the speak method (executes an action).

Let's see this in action.

Python OOP Tutorial 1: Classes and Instances

This next clip from Corey Schafer's video demonstrates how to call the method we just defined and highlights the importance of using parentheses.

Watch from 10:38 to 11:35. The presenter calls employee1.full_name(). See what happens when the parentheses are accidentally left off—it's a common mistake!


3. Why self is Essential

You might wonder why we need to write self as the first parameter in every method definition, even though we don't seem to pass it when we call the method (e.g., employee1.full_name()).

This is a bit of Python magic. When you write employee1.full_name(), Python automatically transforms it behind the scenes into Employee.full_name(employee1). It passes the instance (employee1) as the first argument to the method. That's what self becomes.

Forgetting self in your method definition is one of the most common errors for beginners. The following clip explains this TypeError and clarifies what's happening.

Python OOP Tutorial 1: Classes and Instances

This final clip from the Corey Schafer video demystifies the self parameter and the error that occurs when you forget it.

Watch from 11:35 to 14:07. This is a very important concept. The Error (11:35-12:37): See the TypeError that results from forgetting self. The Explanation (12:37-14:07): The video clearly shows the two ways of calling a method (instance.method() vs. Class.method(instance)) to explain why self is required.


4. Methods That Change an Object's State

The full_name() method we've seen so far uses instance attributes to return a new value. But methods can also change an object's attributes. This means an object can have a state that its methods can modify.

For example, a Microwave object could have an attribute is_on. A turn_on() method could change this attribute from False to True.

Learn Python OOP in under 20 Minutes

This video from Indently demonstrates how methods can change the internal state of an object. It uses a Microwave class with methods like turn_on() and turn_off().

Watch from 06:24 to 11:29. Focus on how the methods work: A new attribute self.turned_on is added in __init__, starting as False. The turn_on() method checks this attribute and, if False, changes it to True. The turn_off() method does the opposite. The run() method first checks the state of self.turned_on before performing its action.

This concept of state is central to object-oriented programming. Each object maintains its own state (self.turned_on can be True for one microwave and False for another), and its methods operate on that state.


5. Practice: Build a LibraryBook Class

Now it's time to put all these concepts together. You will create a LibraryBook class that has both data and behavior.

Your Task:

  1. Open your code editor and create a new file.
  2. Define a class named LibraryBook.
  3. Implement the __init__ constructor. It should accept two arguments: title and author. It should initialize three attributes:
    • self.title
    • self.author
    • self.is_checked_out (This should be set to False by default inside __init__).
  4. Define a method check_out(). This method should change the is_checked_out attribute to True.
  5. Define another method check_in(). This method should change is_checked_out to False.
  6. Define a method status(). This method should check the value of self.is_checked_out and print a message indicating if the book is "available" or "on loan".
  7. Create an instance of your LibraryBook class (e.g., my_book = LibraryBook("The Hobbit", "J.R.R. Tolkien")).
  8. Test your methods:
    • Call the status() method to see its initial state.
    • Call the check_out() method.
    • Call status() again to confirm the state has changed.
    • Call the check_in() method.
    • Call status() one last time.
Click here to see a possible solution after you've tried it yourself.



# 1. Define the LibraryBook class
class LibraryBook:



    # 2. Implement the __init__ constructor
    def __init__(self, title, author):
        self.title = title
        self.author = author
        self.is_checked_out = False # Default state is available




    # 3. Define the check_out method
    def check_out(self):
        print(f"Checking out '{self.title}'...")
        self.is_checked_out = True




    # 4. Define the check_in method
    def check_in(self):
        print(f"Checking in '{self.title}'...")
        self.is_checked_out = False




    # 5. Define the status method
    def status(self):
        if self.is_checked_out:
            print(f"'{self.title}' by {self.author} is currently on loan.")
        else:
            print(f"'{self.title}' by {self.author} is available.")




# 6. Create an instance
my_book = LibraryBook("The Hobbit", "J.R.R. Tolkien")




# 7. Test the methods
my_book.status()      # Should print "is available"
my_book.check_out()   # Checks the book out
my_book.status()      # Should print "is currently on loan"
my_book.check_in()    # Checks the book back in
my_book.status()      # Should print "is available"


Conclusion

Fantastic work today! You have now learned how to give your objects behavior by defining and calling methods. This bridges the gap between just storing data and creating dynamic components that can perform actions and manage their own state.

Key Takeaways:

  • Methods are functions defined inside a class that give objects behavior.
  • Methods are called using dot notation with parentheses: my_object.my_method().
  • The first parameter of every instance method is self, which refers to the object instance the method is being called on. Python passes this argument automatically.
  • Methods can access instance attributes (self.attribute) to read data.
  • Methods can also modify instance attributes, changing the object's internal state.

In the next lesson, we will focus on creating multiple instances of a class and managing their individual state. This will reinforce everything we've learned about __init__ and methods by showing how you can create and manage many independent objects from a single class blueprint.