Classes in Python

Sometimes it's nice to group functions together, and store values that those functions can use. Let's look at an example of a class:

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

    def print_user(self):
        print(self.username)
        print(self.password)

If we run this code:

user = User('user33', 'secret')
user.print_user()

the result is:

user33
secret

The init function above is called an initializer. When we create a user with this line:

user = User('user33', 'secret')

the init function is automatically called by Python. Our init function:

def __init__(self, username, password):
    self.username = username
    self.password = password

takes two parameters, and sets the values of two instance variables, so the print_user function can use them later.

Next: Threads in Python 3

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.