DSA Python - Python class initializer - Tech tutorial - Udacity Instructor Series

How to set up classes with Python class initializer.

It’s common for Python beginners to learn to write one line of code at a time. For example, you can write the following line of Python code to print “Hello World” to your screen:

print(“Hello World”)

You can also define a variable with one short line of Python code:

my_variable = 7

After progressing beyond the beginner level, it’s important to learn how Python can group individual lines of code together in useful ways. In Python, it’s possible to write functions and classes: both are multi-line blocks of code that perform useful purposes.

 In this post, we’ll talk about what functions and classes are. Our main focus will be the class initializer – a special block of code that enables you to set up classes.

Python functions.

Suppose that you’re writing Python code for an app. You want your app to greet users by name. You can write a simple Python function that accomplishes this as follows:

def greet(username):
    print("Hello " + username)

You can see that we start with the “def” keyword. This means that we’re defining something – in particular, we’re defining a function called “greet()”. Inside the parentheses of our greet() function, you can see there’s a variable called “username”. We call that the function’s “argument.” The function can do whatever it wants with that argument. In this case, the function includes that argument in a print() statement, saying hello. You can see what this function does by running the following code:

greet('Robinson Crusoe')

You’ll see the following output:

Hello Robinson Crusoe

The function took the argument we passed to it (“Robinson Crusoe”), and used it to print a simple greeting. This function is simple, but it’s possible to make functions that are much more complex. Let’s add just a little to this function:

def greet(username,number_of_visits):
    print("Hello " + username)
    print("You have used this app " + str(number_of_visits) + " times.")

Now, we have two arguments instead of one, and two print statements instead of one. Our greet() function will now say hello to users, and also tell them how many times they’ve used the app.

Creating a class with an initializer.

Greeting users is useful, but if you’re building an app, you’ll need to do more with users than just greet them. It will be helpful if you can create an object in Python that will store everything you know about your users in a way that’s easy to set up, easy to access, and easy to work with. In Python, you can accomplish that by creating a “class,” a special type of object that makes many advanced Python tasks easier.

Let’s look at a simple example of a class:

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

Here, we created a class called User. You can see that inside this class, we used the “def” keyword to define something that looks like a function. The code block that looks like a function is called __init__(), and it has two arguments.

This __init__() object is similar to a function. It accepts arguments (“self” and “username”) just like a function would, and it contains code just like a function should. But since __init()__ is part of a class, we call it a “method” instead of a function.

Every class is supposed to have an __init__() method. It’s commonly called the constructor of the class. It’s also called the initializer of the class, or the class initializer. You can think of it as the block of code that helps set up every instance of a class. 

Let’s look at an example to make the idea of a class initializer clear.

Example: creating and greeting users.

So far, we’ve gone over the following code for a greet() function and a class called User:

def greet(username,number_of_visits):
    print("Hello " + username)
    print("You have used this app " + str(number_of_visits) + " times.")

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

Now that we’ve defined a class and a function, let’s do what’s called “instantiating” our User class:

JH = User("Jim Hawkins")

This line of code created a new instance of the User class we defined. We could also say that it “instantiated” our User class. Or, more simply, we could say that we created a new user. To create this new user, Python ran the code in our __init()__ method, which is the User class’s initializer. Our class initializer is quite simple: all it does is take an argument (the username) and assign it to something called self.name.

The self.name object is something called an attribute, meaning a piece of information related to our class. Every user should have a user name, so when creating a new user, our class requires an argument that will specify that user’s user name. Our initializer, the __init()__ method, is what makes sure that user name is associated with the right user.

After creating a user, you can access any attributes you’ve defined for that user. For example:


This will print out the user name of the user called JH (in this case, it’s “Jim Hawkins”). We’re able to access this attribute because our initializer defined it when the JH user was created. Our initializer is doing its job!

We can create as many users as we want, and do anything we want with them. For example, let’s create another new user, and call our greet() function to say hello to them:

JS = User("John Silver")

You should see the following output:

Hello John Silver
You have used this app 12 times.

Learn and practice more Python.

As you continue to progress in your Python education, you’ll learn how to use classes to accomplish advanced, complex tasks. But no matter how sophisticated your class is, it should always have a class initializer to set important attribute values and create new instances of your class.

If you’re interested in learning more about Python topics like class initializers, check out Udacity’s Intermediate Python Nanodegree.