Skip to content

Module 11 · Object-Oriented Programming — topic 2 of 25

Classes

Defining a class with the class statement, naming conventions, the class body, class objects versus instances, and inspecting classes with type() and isinstance().

Beginner 10 min read·Lesson 159 of 306 in Python Programming

Learning objectives

  • Write a class definition with methods
  • Create instances by calling the class
  • Use type() and isinstance() with your own classes

Definition

A class is a user-defined type created with the class statement. Its body defines attributes and methods shared by all instances; calling the class like a function creates a new instance.

Introduction

A class statement creates a new type, just as str and list are types. After class Book: ..., you can create books with Book() and check them with isinstance(x, Book).

Why it matters

Designing your own types lets your code speak the language of the problem: Order, Invoice, Player, Room — instead of anonymous dictionaries.

Detailed explanation

Syntax: class Name: followed by an indented body. Class names use PascalCase (BankAccount).

The body usually contains method definitions (def inside the class) and sometimes class-level variables. pass can be used for an empty class.

Running the class statement creates a class object bound to the name. Calling it — Book() — creates an instance and runs __init__ if defined.

type(obj) returns an object's class; isinstance(obj, Class) checks whether obj is an instance of the class (or a subclass).

Every instance has its own namespace for data (stored in obj.__dict__), while methods live on the class and are shared.

Syntax

Python
class Book:
"""A book in a library."""
def __init__(self, title, author):
self.title = title
self.author = author
def describe(self):
return f"{self.title} by {self.author}"
b = Book("Clean Code", "Robert Martin")
  • Class names use PascalCase.
  • Methods are defs inside the class.
  • Calling the class creates an instance.

Code examples

A minimal class

Python
class Empty:
pass
e = Empty()
print(type(e).__name__, isinstance(e, Empty))
e.note = "attributes can be added"
print(e.note)
Output
Empty True
attributes can be added

A class with methods

Python
class Book:
"""A book in a library."""
def __init__(self, title, author):
self.title = title
self.author = author
def describe(self):
return f"{self.title} by {self.author}"
b = Book("Clean Code", "Robert Martin")
print(b.describe())
print(Book.__doc__)
Output
Clean Code by Robert Martin
A book in a library.

More examples

Classes as types

Python
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def is_long(self):
return self.pages > 300
shelf = [Book("Python Basics", 220), Book("Algorithms", 1312), "not a book"]
for item in shelf:
if isinstance(item, Book):
print(item.title, "long" if item.is_long() else "short")
else:
print("skipping", type(item).__name__)
print(vars(shelf[0]))
print(Book.is_long(shelf[1]))
Output
Python Basics short
Algorithms long
skipping str
{'title': 'Python Basics', 'pages': 220}
True

Step-by-step explanation

  • isinstance filters the mixed list so only Book objects are asked for is_long().
  • vars(obj) shows the instance's own attributes as a dictionary.
  • Book.is_long(shelf[1]) calls the method through the class, passing the instance explicitly — exactly what shelf[1].is_long() does behind the scenes.

Expected output

Running “Classes as types” prints exactly:

TextOutput
Python Basics short
Algorithms long
skipping str
{'title': 'Python Basics', 'pages': 220}
True

Practical applications

  • Domain models: Customer, Order, Product.
  • Data containers for API responses.
  • Custom exceptions are classes too.

Best practices

  • Use PascalCase and a docstring for every class.
  • Define attributes in __init__, not by adding them later from outside.
  • Prefer isinstance over comparing type() directly.

Common mistakes

Forgetting parentheses when creating an instance

Avoid

b = Book
b.title = "X" # sets an attribute on the class itself

Prefer

b = Book("X", "Y")

Without parentheses you refer to the class, not a new instance.

lowercase class names

Avoid

class bank_account: ...

Prefer

class BankAccount: ...

PEP 8 uses PascalCase for classes so they are easy to tell apart from functions.

Important notes

  • Classes are themselves objects (instances of type), which is why you can pass them around and inspect them.

Key takeaways

  • class Name: creates a new type.
  • Calling the class creates an instance.
  • type() and isinstance() work with your classes.

Try it yourself

  1. 1
    Define a Rectangle class with width, height and area() and perimeter() methods.
  2. 2
    Create a list of three rectangles and print the largest by area.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic