Your browser does not support JavaScript!
Upvotes Anonymous 0 User 0

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. 
Was this helpful?

Tags

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License