Skip to main content

Unit 6 · Class is in Session · Lesson 48 of 57

Methods to the Madness

Methods to the madness

Our User has data now. But remember, objects are data and methods. Let's give it something to do.

A method is just a function that lives inside a class:

class User:
    def __init__(self, username, role):
        self.username = username
        self.role = role

    def greet(self):
        return f"Hi, I'm {self.username}!"

karl = User("karl", "admin")
print(karl.greet())
Hi, I'm karl!

Same deal as __init__: when you call karl.greet(), Python passes karl in as self for you. So inside greet, self.username is Karl's username.

Call amer.greet() instead, and self is Amer. Same method, different object, different answer.

Every method needs self as its first thing, even if it doesn't use anything else. Watch what happens if you forget it:

Run it and read the last line of the traceback.

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Takes 0 arguments but 1 was given?!

TypeError: User.greet() takes 0 positional arguments but 1 was given

We didn't give it anything! We just wrote karl.greet()!

But Python did. It snuck karl in as self, like it always does... and greet had nowhere to put it. That's why every method starts with self.

Add a method called is_admin to the User class.

It should return True if the user's role is "admin", and False if it's anything else.

User("karl", "admin").is_admin()   # True
User("alex", "banned").is_admin()  # False

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.