Classes & Objects
A class is a blueprint; objects are instances made from it.
Syntax
class Name:
...A class is a blueprint for creating objects. An object (or instance) is a specific thing built from that blueprint, with its own data.
Making objects
Define a class with the class keyword, then call it like a function to create an instance.
Example
class Dog:
pass
rex = Dog()
fido = Dog()
print(type(rex))
print(rex is fido)
# Output:
# <class '__main__.Dog'>
# FalseWhen to use it
- A banking app models an Account as a class with balance and transaction methods.
- A game defines an Enemy class to share behaviour across multiple monster types.
- A REST API serialiser maps each resource type (User, Product, Order) to its own class.
More examples
Define a simple class
Defines a class with a class-level attribute and an instance method, then creates an object.
class Dog:
species = 'Canis lupus familiaris'
def bark(self):
print('Woof!')
fido = Dog()
fido.bark() # Woof!
print(Dog.species) # Canis lupus familiarisMultiple instances share methods
Shows that two instances share the same method but each has its own independent state.
class Counter:
def increment(self):
self.value = getattr(self, 'value', 0) + 1
a = Counter()
b = Counter()
a.increment()
a.increment()
b.increment()
print(a.value, b.value) # 2 1Class with class and instance attribute
Contrasts a shared class attribute (tax_rate) with per-instance attributes (name, price).
class Product:
tax_rate = 0.10 # class attribute shared by all
def __init__(self, name, price):
self.name = name # instance attribute
self.price = price
p = Product('Book', 20)
print(p.name, p.price * (1 + Product.tax_rate))
# Output: Book 22.0
Discussion