Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 15

Defining a Simple Python Class

Recommended resources

Hello! Welcome back to our introduction to Object-Oriented Programming (OOP).

In our last lesson, we focused on the core concepts behind OOP. You learned that a class is like a blueprint, defining the structure and behaviors for a type of thing, while an object (or instance) is an actual, unique item created from that blueprint. We used analogies like a house blueprint and the physical houses built from it.

Today, we'll move from theory to practice. Your goal for this lesson is to learn the Python syntax for creating your own blueprints. You will define a simple class in Python using the class keyword. This is the first step in creating your own custom data types.


1. The class Keyword: Your Blueprinting Tool

In Python, the tool for creating a class is the class keyword. The syntax is simple and follows the same pattern of colons and indentation you've seen with functions and loops.

To get started, let's read a short but very clear explanation of this syntax.

Defining Classes in Python | class Keyword

This article explains the fundamental syntax for defining a class in Python. It's the perfect starting point for turning our conceptual 'blueprint' into actual code.

Read the entire section titled 'Defining a Class'. Pay close attention to these three things: The class keyword itself. The CamelCase naming convention for classes (e.g., MyClass instead of my_class). The use of the pass statement as a placeholder for an empty class body.

As the article explained, the simplest possible class definition looks like this:

class Dog:
    pass

Let's break that down:

  • class: This keyword tells Python we are defining a new class.
  • Dog: This is the name of our class. By convention, class names start with a capital letter and use CamelCase.
  • :: The colon signifies the start of the class's body.
  • pass: Because Python expects an indented block of code after the colon, we use pass as a placeholder. It means "do nothing" and allows us to define the class structure without adding any details yet.

2. Practice: Write Your First Class

Now it's your turn. Open your code editor (like VS Code or Thonny) and type the following code into a new file. This act of typing it yourself helps build muscle memory.




# This code defines a blueprint for creating 'Dog' objects.
# For now, the blueprint is empty.
class Dog:
    pass




# This code creates an actual object (an instance) from the Dog class.
dog1 = Dog()




# We can create another, separate object from the same class.
dog2 = Dog()




# Let's print them to see what they are.
print(dog1)
print(dog2)

When you run this file, you will see an output similar to this (the numbers, which are memory addresses, will be different on your machine):

<__main__.Dog object at 0x10e8d3e50>
<__main__.Dog object at 0x10e8d3e80>

This output confirms two things:

  1. You have successfully created two Dog objects.
  2. dog1 and dog2 are separate, unique objects, each stored at a different memory address.

This process of creating an object from a class is called instantiation. The following video provides a great recap of defining an empty class and then instantiating objects from it.

Python OOP Tutorial 1: Classes and Instances

Let's watch a short clip that demonstrates exactly what you just did: defining a simple class and creating unique instances from it.

Watch from 01:38 to 03:08. Notice how a simple Employee class is defined with pass, and then two unique Employee objects are created from it. This reinforces the concept that you are creating separate objects from a single blueprint.


3. Adding Behavior with Methods

An empty class isn't very useful. The real power comes from bundling behaviors (functions) and data (variables) inside the class definition. A function defined inside a class is called a method.

Let's see how to add a method to a class.

#49 Python Tutorial for Beginners | Class and Object

The next step is to add behaviors to our blueprint. This video shows how to define a 'method' inside a class.

Watch from 01:18 to 02:37. The video explains that classes contain attributes (variables) and behaviors (methods). Focus on how the config method is defined using def inside the Computer class. You will see a keyword self as the first parameter. Don't worry about what self means for now; just know that you must include it. We will cover it in detail in a future lesson.

As you saw, defining a method looks just like defining a function, but it's indented inside the class block.

Let's update our Dog class. Remove the pass statement and add a bark method.

class Dog:



    # This is a method. It defines a behavior for Dog objects.
    # Note the 'self' parameter. It's required for all methods.
    def bark(self):
        print("Woof!")




# Now, let's create a Dog object and make it bark.
my_dog = Dog()




# We call the method on the object using dot notation.
my_dog.bark()

Try it yourself! Modify your Dog class code to include the bark method. Create an instance and call the method. When you run it, you should see Woof! printed to the console.



Conclusion

Congratulations! You've successfully made the leap from understanding the concept of a class to writing one in Python.

Key Takeaways:

  • You define a class using the class keyword followed by a name (in CamelCase) and a colon.
  • The body of the class is indented. You can use pass as a placeholder for an empty class.
  • You create an object (instance) from a class using the syntax my_object = ClassName().
  • Functions defined inside a class are called methods. They define the object's behavior.
  • You call a method on an object using dot notation, like my_object.my_method().

Our Dog class is a good start, but every Dog object we create is identical. We can't give them unique names, ages, or breeds yet. How do we create a dog named "Fido" and another named "Rex"?

In the next lesson, we will solve this problem by learning how to use a special method, the constructor (__init__), to initialize each object with its own unique data right when it's created.