Python Classes & Objects
Python is an object-oriented language: every value — a number, a string, a function — is an object. A class is a blueprint that describes what data an object holds and what it can do. An object (or instance) is one concrete thing built from that blueprint.
Think of a class Car as the design drawing, and my_car and your_car as two actual cars built from it. They share the same design, but each has its own colour and mileage.
Defining a class
class Dog:
pass
rex = Dog()
luna = Dog()
print(type(rex).__name__)
print(rex is luna)
print(isinstance(luna, Dog))Dog
False
True
Class names use PascalCase by convention. Calling the class like a function, Dog(), creates a new instance.
The __init__ method and attributes
__init__ runs automatically each time a new object is created. Use it to set the object's starting data, stored as attributes on self:
class Dog:
def __init__(self, name, breed, age):
self.name = name
self.breed = breed
self.age = age
rex = Dog("Rex", "shepherd", 4)
luna = Dog("Luna", "corgi", 2)
print(rex.name, rex.age)
print(luna.name, luna.breed)
luna.age = 3 # attributes can be changed
print(luna.age)Rex 4
Luna corgi
3
What is self?
self is the object the method is working on. When you call rex.bark(), Python actually calls Dog.bark(rex), passing the instance as the first argument. You must list self as the first parameter of every regular method, but you never pass it yourself.
Methods
Methods are functions defined inside a class. They can read and change the object's attributes through self:
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
print(f"Sorry {self.owner}, insufficient funds.")
return self.balance
self.balance -= amount
return self.balance
acct = BankAccount("Nhung", 100)
acct.deposit(50)
acct.withdraw(30)
acct.withdraw(500)
print(acct.owner, "has", acct.balance)Sorry Nhung, insufficient funds.
Nhung has 120
A readable printout with __str__
Printing an object normally shows something like <__main__.Dog object at 0x7f…>. Define __str__ to control what print() and str() show:
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f"'{self.title}' by {self.author} ({self.pages} pages)"
def is_long(self):
return self.pages > 400
b = Book("The Hobbit", "J.R.R. Tolkien", 310)
print(b)
print(b.is_long())'The Hobbit' by J.R.R. Tolkien (310 pages)
False
Class attributes vs instance attributes
An attribute set on self belongs to one object. An attribute defined directly in the class body is shared by all instances:
class Player:
max_health = 100 # class attribute, shared
count = 0
def __init__(self, name):
self.name = name # instance attribute, per object
self.health = Player.max_health
Player.count += 1
a = Player("Ana")
b = Player("Ben")
b.health -= 30
print(a.name, a.health)
print(b.name, b.health)
print("players created:", Player.count)Ana 100
Ben 70
players created: 2
Note: Don't use a mutable class attribute (like a list) for data that should be per-object — all instances would share the same list.
Class methods and static methods
| Kind | Decorator | First parameter | Typical use |
|---|---|---|---|
| Instance method | — | self |
work with one object's data |
| Class method | @classmethod |
cls |
alternative constructors |
| Static method | @staticmethod |
— | helper that belongs with the class |
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, f):
return cls((f - 32) * 5 / 9)
@staticmethod
def is_freezing(celsius):
return celsius <= 0
t = Temperature.from_fahrenheit(212)
print(t.celsius)
print(Temperature.is_freezing(-3))100.0
True
Test yourself
Which method runs automatically when a new object is created?
- __new_object__
- __init__
- __start__
- constructor
What does self refer to inside a method?
- The class itself
- The current module
- The instance the method was called on
- The parent class
Which special method controls the text shown by print(obj)?
- __print__
- __str__
- __text__
- __show__