Create a Class in Python3

So how do you create a class in Python3? What is class? Why do we need a class? All great questions.

My Computer Setup

  • Python3 (Finally getting used to adding parentheses around my print statements )
  • macOS

What is an object?

So let’s go over what a class is. Classes are the preliminary step to creating an object. Classes are the framework to which we as developers spin up objects. We can think of them as plans for creating items. If we were discussing homes, then a class would be the the building plans for a home. Once we create a home using those plans then we have an object. The home you built is that object. Then we could open your homes door after the object is created with a homes method. Methods are object related functions, but that’s a bit outside of the scope of this particular article.

So you have building plans for a home ( a class), build that home (an object), and then do things to that object using methods.

Why do you need an object?

Objects make managing item state easier. So let’s say we create 100 home objects as described before. Let’s say that we want to randomly open the door in each of those homes. If we wanted to keep track of those doors we could record that info in an array or dictionary and use some sort of ids to match that data back to each home orrrrr we could set the home_open variable in each of those objects to true or false. Then we could just check the specific homes value on be on our way.

Let’s make some home plans or a class

class Home:
    def __init__(self):
        self.door_open = False
    def toggle_door(self):
        self.door_open = not self.door_open
        print('opening your door')

Sooo, this is a class. This house’s door can be opened or closed with the toggle_door method. We can check on the status of the door by getting the door_open variable.

Let’s make an Object

# Copy and paste the code we defined above into your python console
class Home:
    def __init__(self):
        self.door_open = False
    def toggle_door(self):
        self.door_open = not self.door_open
        print('opening your door')

# Now we can instantiate a home object
new_home = Home()
# We an check on the status of our new_home objects door with this
new_home.door_open

# Now if we wanted to open the door we can do the following
# Don't forget the parentheses
new_home.toggle_door() 

# Lets check on your door again
new_home.door_open

So, there you have it. You created a Home class, instantiated an object using that class, and executed a method that affects the objects state. We’ll go deeper into this in the future. Check out this article if you’re still hungry for some Python. And that’s how you create a class in Python3. Happy coding!

Let’s See that Class and Method in Action!

Leave a Comment