Unit 6 · Class is in Session · Lesson 47 of 57
Blueprints
Blueprints
Let's make our own class. Every user on a website has a username and a role, so let's make a User blueprint:
class User:
pass
class works like def: a name, a :, and an indented body. pass just means "nothing here yet."
Now we can build users from it, by calling the class like a function:
karl = User()
karl is now a User object. It's empty, but we can stick data onto it with a .:
karl.username = "karl"
karl.role = "admin"
print(karl.username)
karl
Values stored on an object like this are called attributes.
Cool! Now do the rest of the team. Try it!
Make a User for amer (role user) and zain (role admin) the same way, then print both of their usernames. Feel the pain.
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.
There's a better way
Three lines for every single user. Do that for 500 users, mistype rol instead of role once, and good luck finding it.
What we really want is to hand over the username and role while we're making the user, like this:
karl = User("karl", "admin")
That's what __init__ is for:
class User:
def __init__(self, username, role):
self.username = username
self.role = role
karl = User("karl", "admin")
amer = User("amer", "user")
print(amer.role)
user
__init__ (short for initialize, with two underscores on each side) is a special function inside the class. Python runs it automatically every time you build a new object.
So what's self?
When you write User("amer", "user"), here's what Python does:
- Builds a brand new, empty
Userobject. - Calls
__init__, and passes that new object in asself."amer"goes intousername, and"user"goes intorole. self.username = usernamesticks the username onto that new object.- Hands you back the finished object, which gets stored in
amer.
So self just means "the object being worked on right now." Inside __init__, self.username = username means "MY username is whatever username I was given."
You never pass self in yourself. Python does it for you. That's why User("amer", "user") only has two things in it, even though __init__ has three.
Zain wants to keep track of the routers on his network.
Make a class called Router with an __init__ that takes a name and an ip, and stores them as self.name and self.ip.
Then make one called office with the name Office Router and the IP 192.168.1.1, and print its IP.
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.