Skip to main content

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

Family Tree

Family tree

Admins are users too. They have a username, a role, and they can greet() like everyone else. They can just do a little more.

You could copy and paste the whole User class and add to it. But then every time you fix something in User, you'd have to fix it in two places.

Instead, a class can inherit from another one:

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

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


class Admin(User):
    def ban(self, other):
        other.role = "banned"

class Admin(User) means "an Admin is a User, plus whatever I add here." Admins get __init__ and greet from User for free, and they also get ban.

karl = Admin("karl", "admin")
alex = User("alex", "user")

print(karl.greet())
karl.ban(alex)
print(alex.role)
Hi, I'm karl!
banned

karl.greet() works even though Admin never defined greet. Python looks in Admin first, doesn't find it, and checks the parent class, User.

Notice ban takes another user. self is the admin doing the banning, and other is the one getting banned.

Why this matters for security

Remember authentication and authorization? Classes like this are how a lot of real websites handle "who's allowed to do what." Regular users simply don't have a ban method. Only admins do.

Add a class called Admin that inherits from User, with two methods:

  • ban(self, other) sets the other user's role to "banned"
  • promote(self, other) sets the other user's role to "admin"

Don't change User!

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.