DEV Community

Kajiru
Kajiru

Posted on

Getting Started with Python (Part 12): Using Classes

Using Classes

In this article, you’ll learn about classes in Python.

To understand classes, you first need to understand the concept of objects.


What Is an Object?

An object is a combination of data and the functions that operate on that data.

It’s easy to imagine an object as a single game character or a user in an application.


What Is a Class?

A class is a blueprint for creating objects.

Based on this blueprint (class), you create actual objects called instances.

By using classes properly, you can write cleaner and more manageable programs through techniques such as:

  • Data protection (encapsulation)
  • Separation of responsibilities

1. Defining a Class

You can define a class using the class keyword as shown below.

class ClassName:
    """ Class definition """
Enter fullscreen mode Exit fullscreen mode

2. What Is the Initialization Method?

A special method that runs only once when an instance is created is called the initialization method.

As the name suggests, it is used to initialize data.

The initialization method uses the special method name __init__ after the def keyword.

The first parameter must always be self.

The self parameter refers to the instance itself that called the method.

class ClassName:
    """ Class definition """
    def __init__(self):
        """ Initialization method """
Enter fullscreen mode Exit fullscreen mode

3. What Are Instance Variables?

Data defined inside a class is called instance variables.

Instance variables are declared and initialized inside the initialization method using the format:
self.variable_name.

class ClassName:
    """ Class definition """
    def __init__(self):
        """ Initialization method """
        self.variable_name = "data"
Enter fullscreen mode Exit fullscreen mode

4. What Are Instance Methods?

Functions defined inside a class are called instance methods.

Instance methods are defined using the def keyword.

Just like the initialization method, the first parameter must be self.

class ClassName:
    """ Class definition """
    def __init__(self):
        """ Initialization method """
        self.variable_name = "data"

    def instance_method_name(self):
        """ Instance method """
Enter fullscreen mode Exit fullscreen mode

Using a Class

The following example shows the full flow:

  • Defining a class
  • Creating instances
  • Calling methods
class User:
    """ Class definition """
    def __init__(self, nick_name, real_name):
        """ Initialization """
        self.nick_name = nick_name  # Instance variable
        self.real_name = real_name  # Instance variable

    def greeting(self):
        """ Instance method """
        print(f"{self.nick_name}'s real name is {self.real_name}!!")

    def say_something(self, word):
        """ Instance method """
        print(f'{self.nick_name}: "{word}"')


user1 = User("Maruko", "Momoko Sakura")  # Create instance
user1.greeting()
user1.say_something("Hmm... how mean~")
# Maruko's real name is Momoko Sakura!!
# Maruko: "Hmm... how mean~"

user2 = User("Tama-chan", "Tamae Honami")
user2.greeting()
user2.say_something("Maruko...")
# Tama-chan's real name is Tamae Honami!!
# Tama-chan: "Maruko..."

user3 = User("Maruo-kun", "Sueo Maruo")
user3.greeting()
user3.say_something("Precisely speaking, total annihilation!!")
# Maruo-kun's real name is Sueo Maruo!!
# Maruo-kun: "Precisely speaking, total annihilation!!"
Enter fullscreen mode Exit fullscreen mode

Final Words

Thank you very much for reading this book to the end.

So far, you’ve learned the fundamentals of Python programming, including:

  • Variables
  • Functions
  • Data structures
  • Exception handling
  • Classes

This book was designed to focus on areas where beginners often struggle,

and to cover “just enough to get you started with confidence.”

Your real programming journey starts here.

The knowledge you’ve gained will be useful in many fields, such as:

  • Web development
  • Automation
  • Data analysis
  • Game development (this one’s especially fun!)

May your Python journey be enjoyable and rewarding. 🐍✨

Top comments (0)