Programming fundamentals · Beginner · 20 min
Write your first class in Python: objects, attributes and methods
By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)
You will model a library book loan as a Python class with attributes, methods, a readable __repr__ and a shared loan period, compare it with a dictionary version, rewrite it as a dataclass and end with a Loan class and a short script that uses it.
On this page
So far your programs have kept data in variables, lists and dictionaries, and kept behaviour in functions. That works until the data and the functions that change it start drifting apart: a function expects a key the dictionary does not have, or two parts of the program disagree about how long a loan lasts. A class puts the data and the functions that belong to it in one place.
In this tutorial you model one thing a small library tracks: a book loan. A loan has a title, a borrower and a due date, it can be checked out and returned, and every loan lasts the same number of days. You build it up one idea at a time, run each version and read its output. Then you write the same thing with a dictionary and plain functions, so you can judge when a class is worth it, and finish with a shorter version using @dataclass.
The dates are fixed in the code (2 November 2026 and so on) so your output matches the text exactly. In a real program you would use date.today().
The examples use python3. On Windows outside WSL, type py instead. On an Android phone, the Termux app installs Python with pkg install python, and everything here runs offline without using mobile data.
Step 1 · Make an empty class and your first object
Make a folder for this tutorial and write the smallest class Python allows:
mkdir -p ~/loan-demo
cd ~/loan-demo
cat > empty.py <<'PY'
class Loan:
pass
first = Loan()
second = Loan()
print(type(first))
print(first is second)
first.title = "Things Fall Apart"
print(first.title)
PY
python3 empty.pyLine by line:
class Loan:starts a class definition.Loanis its name; class names use CapitalisedWords by convention, so you can tell them apart from functions at a glance. The indented block below it is the class body.passmeans "nothing here yet". A body cannot be empty, sopassfills the gap.first = Loan()calls the class like a function. That creates a new object, also called an instance of the class, andfirstrefers to it.second = Loan()creates a second, separate object from the same class.type(first)asks what kind of thingfirstis.first is secondchecks whether both names refer to the same object.first.title = "Things Fall Apart"attaches an attribute, a named value stored on the object, andfirst.titlereads it back. The dot means "thetitlethat belongs tofirst".
A class is the blueprint; each object made from it is one loan with its own data.
Check it worked
The output is three lines: <class '__main__.Loan'>, then False (two calls made two different objects), then Things Fall Apart. The __main__ part means the class was defined in the script you ran directly.
Step 2 · Give every loan its attributes with __init__
Adding attributes by hand after creating each object is easy to get wrong: forget one and the object is incomplete. A method called __init__ runs automatically every time an object is created, so every loan starts with the same set of attributes:
cat > init.py <<'PY'
class Loan:
def __init__(self, title, borrower):
self.title = title
self.borrower = borrower
self.due = None
self.returned = False
a = Loan("Things Fall Apart", "Amara")
b = Loan("Half of a Yellow Sun", "Kofi")
print(a.title, "->", a.borrower)
print(b.title, "->", b.borrower)
print(a.due, a.returned)
b.borrower = "Wanjiru"
print(a.borrower, b.borrower)
PY
python3 init.pyWhat is new:
def __init__(self, title, borrower):is a function defined inside the class. A function that belongs to a class is called a method. The double underscores on each side mark a name Python itself calls at a set moment; for__init__, that moment is object creation.selfis the object being set up. When you writeLoan("Things Fall Apart", "Amara"), Python creates an empty object, then calls__init__with that object asself,"Things Fall Apart"astitleand"Amara"asborrower. You never passselfyourself.self.title = titlestores the parameter on the object. The left side is the attribute that lives on as long as the object; the right side is the parameter, which disappears when__init__ends. Using the same name for both is normal.self.due = Noneandself.returned = Falseare starting values the caller does not choose: a new loan has no due date yet and has not been returned.b.borrower = "Wanjiru"changes one attribute on one object.
Check it worked
The output is:
Things Fall Apart -> Amara
Half of a Yellow Sun -> Kofi
None False
Amara WanjiruThe last line is the important one: changing b.borrower left a.borrower alone. Each object keeps its own copy of its attributes.
Step 3 · Add methods that change the loan
A loan is checked out and later returned. Those actions change the object's attributes, so they belong on the class as methods. Write the class to its own file, loan.py, so later steps can import it:
cat > loan.py <<'PY'
from datetime import timedelta
class Loan:
def __init__(self, title, borrower):
self.title = title
self.borrower = borrower
self.due = None
self.returned = False
def check_out(self, today):
self.due = today + timedelta(days=14)
self.returned = False
def return_book(self, today):
if self.due is None:
raise ValueError(f"{self.title!r} was never checked out")
self.returned = True
days_late = (today - self.due).days
return max(days_late, 0)
PY
cat > methods.py <<'PY'
from datetime import date
from loan import Loan
loan = Loan("Things Fall Apart", "Amara")
loan.check_out(date(2026, 11, 2))
print("due:", loan.due, "returned:", loan.returned)
late = loan.return_book(date(2026, 11, 20))
print("returned:", loan.returned, "days late:", late)
other = Loan("Purple Hibiscus", "Kofi")
other.return_book(date(2026, 11, 20))
PY
python3 methods.py || echo "exit status $?"How the methods work:
from datetime import timedeltabrings intimedelta, a length of time you can add to a date. The caller passes indateobjects, whichmethods.pyimports.def check_out(self, today):takesselffirst, like every method, then the date of checkout.self.due = today + timedelta(days=14)sets the due date two weeks later.return_bookrefuses to return a loan that was never checked out:raise ValueError(...)stops with an error message instead of quietly storing nonsense.!rinside the f-string prints the title with quotes.(today - self.due).dayssubtracts two dates, which gives atimedelta, and.daysis its length in whole days.max(days_late, 0)turns an early return (a negative number) into 0. A method can return a value like any function.loan.check_out(date(2026, 11, 2))calls the method. Python turns this intoLoan.check_out(loan, date(2026, 11, 2)): the object before the dot becomesself. That is why you define methods withselfbut call them without it.from loan import Loanloads the class fromloan.pyin the same folder.
Check it worked
The first two lines are due: 2026-11-16 returned: False and returned: True days late: 4. The last call fails on purpose: you see a traceback ending in ValueError: 'Purple Hibiscus' was never checked out, then exit status 1.
The most common beginner mistake with methods is leaving out self in the definition, as in def check_out(today):. Calling loan.check_out(...) then fails with a TypeError saying the method takes 1 positional argument but 2 were given. The hidden second argument is the object itself.
Step 4 · Print loans readably with __repr__
Print a loan object and Python shows its class and memory address, which tells you nothing about the loan. Add a __repr__ method to loan.py, which Python calls whenever it needs a text description of the object for a developer. Replace the whole file:
cat > repr_before.py <<'PY'
from loan import Loan
print(Loan("Things Fall Apart", "Amara"))
PY
python3 repr_before.py
cat > loan.py <<'PY'
from datetime import timedelta
class Loan:
def __init__(self, title, borrower):
self.title = title
self.borrower = borrower
self.due = None
self.returned = False
def check_out(self, today):
self.due = today + timedelta(days=14)
self.returned = False
def return_book(self, today):
if self.due is None:
raise ValueError(f"{self.title!r} was never checked out")
self.returned = True
days_late = (today - self.due).days
return max(days_late, 0)
def __repr__(self):
return (
f"Loan(title={self.title!r}, borrower={self.borrower!r}, "
f"due={self.due}, returned={self.returned})"
)
PY
cat > repr_after.py <<'PY'
from datetime import date
from loan import Loan
loans = [Loan("Things Fall Apart", "Amara"), Loan("Half of a Yellow Sun", "Kofi")]
loans[0].check_out(date(2026, 11, 2))
print(loans[0])
print(loans)
PY
python3 repr_after.py__repr__ takes only self and must return a string; it does not print anything itself. The convention is to make the string look like the code that would create the object, so anyone reading a log or debugging output sees exactly what the object holds. print uses it, and so do lists when they show their contents.
Check it worked
Before the change, the output is something like <loan.Loan object at 0x7f3a2c1d5e50>; the address differs on every run. After it, the output is:
Loan(title='Things Fall Apart', borrower='Amara', due=2026-11-16, returned=False)
[Loan(title='Things Fall Apart', borrower='Amara', due=2026-11-16, returned=False), Loan(title='Half of a Yellow Sun', borrower='Kofi', due=None, returned=False)]Each object in the list prints its own data, which confirms again that every loan keeps its own attributes.
Step 5 · Share the loan period with a class attribute
The number 14 is buried inside check_out. Every loan uses the same period, so it belongs to the class, not to each object. A variable written directly in the class body, outside any method, is a class attribute: one value shared by all instances. Change loan.py so the period is defined once:
cat > loan.py <<'PY'
from datetime import timedelta
class Loan:
loan_days = 14
def __init__(self, title, borrower):
self.title = title
self.borrower = borrower
self.due = None
self.returned = False
def check_out(self, today):
self.due = today + timedelta(days=self.loan_days)
self.returned = False
def return_book(self, today):
if self.due is None:
raise ValueError(f"{self.title!r} was never checked out")
self.returned = True
days_late = (today - self.due).days
return max(days_late, 0)
def __repr__(self):
return (
f"Loan(title={self.title!r}, borrower={self.borrower!r}, "
f"due={self.due}, returned={self.returned})"
)
PY
cat > class_attr.py <<'PY'
from datetime import date
from loan import Loan
a = Loan("Things Fall Apart", "Amara")
b = Loan("Half of a Yellow Sun", "Kofi")
print(Loan.loan_days, a.loan_days, b.loan_days)
Loan.loan_days = 21
a.check_out(date(2026, 11, 2))
print("a due:", a.due)
b.loan_days = 7
b.check_out(date(2026, 11, 2))
print("b due:", b.due)
print(Loan.loan_days, a.loan_days, b.loan_days)
PY
python3 class_attr.pyWhat happens here:
loan_days = 14in the class body creates one value stored on the classLoanitself.self.loan_daysinsidecheck_outlooks forloan_dayson the object first. The object has none, so Python looks on the class and finds 14.Loan.loan_days = 21changes the shared value, so every loan that has not overridden it now uses 21 days.b.loan_days = 7does not change the class. It creates a new attribute onbonly, which hides the class value for that one object. This catches people out: assigning through an instance never changes a class attribute.
Check it worked
The output is:
14 14 14
a due: 2026-11-23
b due: 2026-11-09
21 21 7a used the shared 21 days, b used its own 7, and the class still says 21. Delete the override with del b.loan_days and b.loan_days would read 21 again.
Step 6 · Compare the class with a dictionary and functions
You could write the same thing without a class. Here is a loan as a dictionary, with plain functions that take the dictionary as their first argument:
cat > as_dict.py <<'PY'
from datetime import date, timedelta
LOAN_DAYS = 14
def new_loan(title, borrower):
return {"title": title, "borrower": borrower, "due": None, "returned": False}
def check_out(loan, today):
loan["due"] = today + timedelta(days=LOAN_DAYS)
loan["returned"] = False
def return_book(loan, today):
if loan["due"] is None:
raise ValueError(f"{loan['title']!r} was never checked out")
loan["returned"] = True
return max((today - loan["due"]).days, 0)
loan = new_loan("Things Fall Apart", "Amara")
check_out(loan, date(2026, 11, 2))
print(return_book(loan, date(2026, 11, 20)))
print(loan)
PY
python3 as_dict.pyLook at the two versions side by side. new_loan does the job of __init__, and each function's first parameter, loan, does the job of self. The class is not magic: it is this same pattern with the data and functions grouped and named for you.
What the class adds:
- One place to look. Everything a loan can do is listed inside
class Loan. With functions, nothing stops another file from writing its own slightly differentcheck_out. - A type.
type(loan)saysLoan, and you can check it withisinstance(loan, Loan). A dictionary is just a dictionary. - Readable printing and shared settings without extra functions or global variables.
When a dictionary is the better choice: data that arrives as JSON from a file or web API and is mostly read, not changed; data whose keys vary from record to record; and quick scripts where one or two functions touch the data. If you keep writing functions whose first parameter is the same kind of dictionary, that is the sign to turn it into a class.
Check it worked
The output is 4, then {'title': 'Things Fall Apart', 'borrower': 'Amara', 'due': datetime.date(2026, 11, 16), 'returned': True}. The result matches the class version: 4 days late, due 16 November.
Step 7 · Write the same loan as a dataclass
Classes that mainly hold data share a lot of boilerplate: an __init__ that copies each parameter to self, and a __repr__ that lists them again. The dataclasses module in the standard library writes those for you from a list of annotated fields:
cat > loan_record.py <<'PY'
from dataclasses import dataclass
from datetime import date, timedelta
from typing import ClassVar
@dataclass(slots=True)
class LoanRecord:
loan_days: ClassVar[int] = 14
title: str
borrower: str
due: date | None = None
returned: bool = False
def check_out(self, today):
self.due = today + timedelta(days=self.loan_days)
self.returned = False
def return_book(self, today):
if self.due is None:
raise ValueError(f"{self.title!r} was never checked out")
self.returned = True
return max((today - self.due).days, 0)
PY
cat > dataclass_demo.py <<'PY'
from datetime import date
from loan_record import LoanRecord
loan = LoanRecord("Things Fall Apart", "Amara")
print(loan)
loan.check_out(date(2026, 11, 2))
print(loan.return_book(date(2026, 11, 20)), loan)
print(loan == LoanRecord("Things Fall Apart", "Amara", date(2026, 11, 16), True))
try:
loan.retruned = False
except AttributeError:
print("typo caught: AttributeError")
PY
python3 dataclass_demo.pyLine by line:
@dataclass(slots=True)is a decorator: it takes the class written below it and adds generated methods to it.slots=Truealso fixes the list of attributes, so a misspelt one raises an error instead of quietly creating a new attribute.loan_days: ClassVar[int] = 14is the shared loan period. Marking itClassVartells the dataclass it is a class attribute, not a field each loan stores.title: strandborrower: strare fields with type annotations: notes saying what kind of value each should hold. Python does not enforce them at run time; editors and checkers use them. Fields without a default must come first.due: date | None = Nonemeans "a date orNone, starting asNone".returned: bool = Falsehas a default too, so callers can leave both out.- The methods are written exactly as before. A dataclass is still an ordinary class.
Check it worked
The output is:
LoanRecord(title='Things Fall Apart', borrower='Amara', due=None, returned=False)
4 LoanRecord(title='Things Fall Apart', borrower='Amara', due=datetime.date(2026, 11, 16), returned=True)
True
typo caught: AttributeErrorYou wrote no __init__ and no __repr__, yet both exist. The True line shows another generated method, __eq__: two dataclass objects with the same field values compare equal, where two plain Loan objects are only equal if they are the same object. The last line shows slots=True catching the misspelling retruned.
Classes can also inherit from other classes, for example a ReferenceLoan that reuses Loan but cannot leave the building. That is a topic of its own and is left out here on purpose: most first classes, and many good ones, never need it.
Step 8 · Use the Loan class in a short script
Put it to work. This script records a morning at a small library desk: several loans checked out, some returned on different days, and a summary of what is still out and what is overdue. Text in any language works as a title or name, because Python strings are Unicode:
cat > desk.py <<'PY'
from datetime import date
from loan import Loan
loans = [
Loan("Things Fall Apart", "Amara"),
Loan("Half of a Yellow Sun", "Kofi"),
Loan("Weep Not, Child", "Wanjiru"),
Loan("Ìtàn Àròsọ Yorùbá", "Tunde"),
]
for loan in loans:
loan.check_out(date(2026, 11, 2))
fines_per_day = 50
print("late fee:", loans[0].return_book(date(2026, 11, 20)) * fines_per_day)
print("late fee:", loans[1].return_book(date(2026, 11, 10)) * fines_per_day)
today = date(2026, 11, 18)
still_out = [loan for loan in loans if not loan.returned]
overdue = [loan for loan in still_out if loan.due < today]
print("still out:", len(still_out))
for loan in overdue:
print("overdue:", loan.title, "->", loan.borrower, "since", loan.due)
assert loans[0].returned and not loans[2].returned
assert len(overdue) == 2
print("all checks passed")
PY
python3 desk.pyThe script uses everything you built: __init__ through Loan(...), the check_out and return_book methods, the shared loan_days and the attributes. fines_per_day is in whatever currency your library uses. The two list comprehensions pick out loans by reading their attributes, and the assert lines stop the script with an AssertionError if the results are not what you expect.
Check it worked
The output is:
late fee: 200
late fee: 0
still out: 2
overdue: Weep Not, Child -> Wanjiru since 2026-11-16
overdue: Ìtàn Àròsọ Yorùbá -> Tunde since 2026-11-16
all checks passedThe first book came back 4 days late (4 × 50), the second came back early, and the two still out have been due since 16 November. If the Yorùbá title shows as boxes, your terminal font is missing those characters; the data itself is correct.
When you have finished, delete the demo folder:
cd ~
rm -rf ~/loan-demoNext steps
- Move
loan.pyinto a package other scripts can import: split Python code into modules. - Find out why two names can point at the same
Loanobject, and what that means when you change it: references and mutability. - Review parameters, return values and docstrings, which every method uses: write functions that return values.
Related tutorials
- Write your first JavaScript tests with the built-in Node.js test runnerYou will write a small price module in JavaScript, cover it with six passing tests using node:test and node:assert, and know how to read a failure and run one test on its own, with no packages installed.
- Write readable code: names, comments and a formatterYou will turn a working but cryptic Python script into a readable one with clear names, named constants, small functions and useful comments, tidy it with Ruff, prove its output has not changed and leave with your own style checklist.
- Write pseudocode before you codeYou will plan a bus-fare calculator in pseudocode, trace it by hand to find and fix a gap in the plan, draw it as a flowchart and turn it line by line into a Python script that gives the same answers.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials