Python Basics

Python Classes and Objects: A Beginner Example

Bundle data and behavior into your own type. Write a class, create objects from it and call their methods.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • Defining a class with __init__
  • Instance attributes and self
  • Writing and calling methods
One class, many objects
  • class Coursename, lessons, describe()
    • Course("Python Basics", 12)
    • Course("Data Science", 20)
Both objects share the methods but store their own data.

A class is a template

The problem

Say you manage 50 courses, each with a name, a lesson count and a one-line description. With loose variables (name1, lessons1, name2...) or a pile of dictionaries, the code repeats itself, a mistyped key slips through, and the actions for a course end up scattered. A class solves exactly this: it keeps the data and the actions of one kind of thing together.

Think of it like this

A class is like a printed course information form. The form has a box for the course name and a box for the number of lessons, but a blank form is not any course yet. Each time you fill one in, you get one specific course. Every filled-in form can be read out the same way, whichever course it describes.

From a form to code
class Course📄 The blank form: boxes for name and lessons, nothing filled in
Course("Python Basics", 12)✍️ One filled-in form (an object)
self.name, self.lessons🗂️ What is written in the boxes: each form has its own values
describe()📢 Read the form aloud: every form is read the same way
One form, many filled-in copies. One class, many objects.
In one sentence

A class is a type you define yourself that keeps data (attributes) and the functions that work on that data (methods) together. An object is one concrete value created from a class.

Key points

  1. class Course: declares a new type called Course. Calling Course("Python Basics", 12) like a function gives you a new object.
  2. __init__ is the initializer: Python calls it as soon as the object is created, to set starting values such as self.name = name.
  3. self is the object being used. Inside describe(), self.name reads the name of that particular course.
  4. Every object keeps its own attributes: Course("Python Basics", 12) and Course("Data Science", 20) have different lesson counts, and changing one does not touch the other.

When should you use it?

  • You have many things of the same kind with the same set of details: courses, students, products in a cart, characters in a game.
  • The data always comes with its own actions, such as a bank account with a balance plus deposit() and withdraw().
  • You want to check data the moment it is created, for example rejecting a negative lesson count in __init__.

When not to use it

  • You only have a few values used once in a short script: a variable or a dictionary is enough.
  • You only need a calculation that takes input and returns a result, with nothing to remember: a function is simpler.

Example code

Run code →
main.py
class Course:
    def __init__(self, name, lessons):
        self.name = name
        self.lessons = lessons

    def describe(self):
        return f"{self.name}: {self.lessons} lessons"

course = Course("Python Basics", 12)
print(course.describe())
Get a Run button for this example

Result of running the code

Python Basics: 12 lessons

Code explanation

The initializer stores constructor arguments on each instance. The describe method reads that instance state.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in the Python compiler →

Python class syntax at a glance

class Course:Define a class
def __init__(self, name):Constructor: runs when an object is created
self.name = nameStore a value on the object (instance attribute)
course = Course("Python")Create an object
def describe(self):A method; self is the object it is called on
category = "programming"Class attribute shared by every object
class Video(Course):Inherit from another class
super().__init__(name)Call the parent class's constructor
@propertyRead a method like an attribute
def __str__(self):Text shown by print(course)

Common mistakes with Python classes

Forgetting self in a method

Python passes the object as the first argument, so every method needs a self parameter.

Problem
class Course:
    def describe():
        return "A course"

Course().describe()  # TypeError: takes 0 positional arguments but 1 was given
Fix
class Course:
    def describe(self):
        return "A course"

print(Course().describe())

A list as a class attribute

A list defined on the class is shared by every object. Create it in __init__ so each object gets its own.

Problem
class Student:
    grades = []

a, b = Student(), Student()
a.grades.append(90)
print(b.grades)  # [90]
Fix
class Student:
    def __init__(self):
        self.grades = []

a, b = Student(), Student()
a.grades.append(90)
print(b.grades)  # []

Forgetting to call super().__init__

A child class that defines its own __init__ replaces the parent's one, so the parent's attributes are never set.

Problem
class Course:
    def __init__(self, name):
        self.name = name

class Video(Course):
    def __init__(self, name, minutes):
        self.minutes = minutes

print(Video("Python", 30).name)  # AttributeError
Fix
class Course:
    def __init__(self, name):
        self.name = name

class Video(Course):
    def __init__(self, name, minutes):
        super().__init__(name)
        self.minutes = minutes

print(Video("Python", 30).name)  # Python

Frequently asked questions

What is the difference between a class and an object?

A class is the blueprint, and an object (instance) is one thing built from it. Course is a class; Course("Python") creates an object of that class.

What does self mean in Python?

self is the object a method is working on. Python passes it automatically, so course.describe() runs describe with self set to course.

What is __init__ in Python?

__init__ is the method Python calls right after creating an object. Use it to set the object's starting attributes.

How does inheritance work in Python?

Write class Child(Parent):. The child gets all of the parent's methods and attributes and can add or override them; super() calls the parent's version.

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges