1. Classes and Objects
A class is a blueprint. An object (also called an instance) is a thing built from that blueprint.
Think of a class as a cookie cutter and objects as the cookies.
class Dog:
def bark(self):
print("Woof!")
# Create two objects (instances) from the Dog class
rex = Dog()
fido = Dog()
rex.bark() # Woof!
fido.bark() # Woof!
Key points in the above script:
class Dog:defines the blueprint. Class names useCapitalizedWordsby convention, also known asPascalCase.def bark(self):is a method. Which is a function that belongs to a class.selfis the object the method is being called on. Python passes it automatically:rex.bark()is the same asDog.bark(rex).
2. Constructors (__init__)
The constructor is a special method called automatically when you create an object. In Python it is named __init__. Use it to give each object its starting state/data.
class Dog:
def __init__(self, name, age):
self.name = name # store data on the object
self.age = age
def describe(self):
print(f"{self.name} is {self.age} years old.")
rex = Dog("Rex", 3) # calls Dog.__init__(rex, "Rex", 3)
fido = Dog("Fido", 5)
rex.describe() # Rex is 3 years old.
fido.describe() # Fido is 5 years old.
You can also give parameters default values:
class Dog:
def __init__(self, name, age=1):
self.name = name
self.age = age
puppy = Dog("Bean") # age defaults to 1
print(puppy.age) # 1
3. Class Attributes vs Instance Attributes
- Instance attributes belong to one specific object. They are usually set in
__init__usingself. - Class attributes are shared by all objects of the class. They are defined directly inside the class body.
class Dog:
species = "Canis familiaris" # class attribute (shared)
def __init__(self, name):
self.name = name # instance attribute (unique per object)
rex = Dog("Rex")
fido = Dog("Fido")
print(rex.name) # Rex
print(fido.name) # Fido
print(rex.species) # Canis familiaris
print(fido.species) # Canis familiaris
print(Dog.species) # Canis familiaris (you can read it from the class too)
Changing a class attribute on the class affects every object that hasn't overridden it:
Dog.species = "Canis lupus familiaris"
print(rex.species) # Canis lupus familiaris
print(fido.species) # Canis lupus familiaris
Assigning through an instance creates a new instance attribute that hides the class one, for that object only:
rex.species = "Robot Dog"
print(rex.species) # Robot Dog
print(fido.species) # Canis lupus familiaris
Don't use a list or dict as a class attribute if each object (class instance) should have its own copy. All objects would share that one list.
class BadKennel:
dogs = [] # shared by EVERY kennel!
def add_dog(self, dog):
self.dogs.append(dog)
a = BadKennel()
b = BadKennel()
a.add("Rex")
print(b.dogs) # ['Rex'] <- surprise!
class GoodKennel:
def __init__(self):
self.dogs = [] # each kennel gets its own list
def add_dog(self, dog):
self.dogs.append(dog)
a = GoodKennel()
b = GoodKennel()
a.add("Rex")
print(b.dogs) # []
4. Dunder Methods for Strings (__str__ and __repr__)
"Dunder" means double underscore. Dunder methods (like __init__) are special methods Python calls for you in certain situations.
Two of the most useful ones control how an object turns into text.
__str__ and __repr__
Without them, printing an object isn't helpful:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rex = Dog("Rex", 3)
print(rex) # <__main__.Dog object at 0x7f...>
With them:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, age {self.age}"
def __repr__(self):
return f"Dog(name={self.name!r}, age={self.age!r})"
rex = Dog("Rex", 3)
print(rex) # Rex, age 3
print(repr(rex)) # Dog(name='Rex', age=3)
print([rex]) # [Dog(name='Rex', age=3)] <- lists use __repr__ for their items
If you only write one, write __repr__. Python falls back to it when __str__ is missing.
5. The 5 Pillars of OOP
You'll most often hear of four pillars: Abstraction, Encapsulation, Inheritance, Polymorphism. Some sources add a fifth. Here, I added the fifth as Composition, since it's the main alternative to inheritance and is the favored approach when able. It is covered in more depth further down.
Pillar 1: Encapsulation
Bundle data and the methods that work on it together, and protect the data from careless outside changes.
Python doesn't enforce privacy, so it uses naming conventions:
name= Public. Anyone can use it._name= "Protected" by convention. Please don't touch from outside.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance # internal detail, should not be touched directly
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount # 'set' balance by depositing through method
def withdraw(self, amount):
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount # 'set' balance by withdrawing through method
def get_balance(self):
return self._balance # 'get' balance through method only
acct = BankAccount("Sam", 100)
acct.deposit(50)
acct.withdraw(30)
print(acct.get_balance()) # 120
The outside world uses deposit and withdraw, which enforce the rules, instead of changing the balance directly. (Further down shows a more "Pythonic" way using @property for getters and setters.)
Pillar 2: Abstraction
Hide complicated details and expose only what's necessary. Python's abc module lets you define an abstract class: a template that can't be created directly and forces subclasses to fill in required methods.
from abc import ABC, abstractmethod
import math
# Not instantiated directly, only inherited. Methods are defined as a contract that inheriting Classes MUST implement
class Shape(ABC):
# defines method that MUST be implemented in inheriting class
@abstractmethod
def area(self):
# abstract method, not implemented here...
"""Every shape must be able to compute its area."""
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * (self.radius ** 2)
# shape = Shape() # TypeError: Can't instantiate abstract class!
print(Rectangle(3, 4).area()) # 12
print(Circle(2).area()) # 12.56636
Code that uses a Shape only needs to know "it has an area()", not how each shape calculates it.
Pillar 3: Inheritance
A child class (subclass) reuses and extends a parent class (superclass). It models an "is-a" relationship. Example -> a Dog is an Animal.
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print(f"{self.name} says Woof!")
rex = Dog("Rex")
rex.eat() # Rex is eating. (inherited from Animal)
rex.bark() # Rex says Woof! (defined in Dog)
Use super() to call the parent's version of a method, most commonly used in __init__:
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # let Animal set up self.name
self.breed = breed
rex = Dog("Rex", "Beagle")
print(rex.name, rex.breed) # Rex Beagle
Pillar 4: Polymorphism
"Many forms." Different classes can have the same method name, so code can treat them all the same way, without caring about the exact type.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement speak()")
class Dog(Animal):
def speak(self): # overrides Animal.speak
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class Duck(Animal):
def speak(self):
return "Quack!"
# each object inherits speak() but overwrites its implementation
animals = [Dog("Rex"), Cat("Whiskers"), Duck("Donald")]
for animal in animals:
print(f"{animal.name}: {animal.speak()}")
# Rex: Woof!
# Whiskers: Meow!
# Donald: Quack!
The loop doesn't check which kind of animal it has. It just calls speak(), and each object does the right thing.
Pillar 5: Composition
Build complex objects by combining simpler ones. It models a "has-a" relationship: a Car has an Engine. This is covered in detail next.
class Engine:
def start(self):
return "Vroom!"
class Car:
def __init__(self):
self.engine = Engine() # Car HAS-AN Engine
def start(self):
return self.engine.start()
my_car = Car()
print(my_car.start()) # Vroom!
6. Inheritance vs Composition
Both let you reuse code, but they answer different questions:
For example: A Dog is an Animal (inheritance), A Car has an Engine (composition)
Inheritance example
class Vehicle:
def __init__(self, wheels):
self.wheels = wheels
def drive(self):
print(f"Driving on {self.wheels} wheels")
class Motorcycle(Vehicle):
def __init__(self):
super().__init__(wheels=2)
harley = Motorcycle()
harley.drive() # Driving on 2 wheels
Composition example
class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
def start(self):
print(f"Engine ({self.horsepower} hp) started")
class Wheels:
def __init__(self, count):
self.count = count
class Car:
def __init__(self, engine, wheels):
self.engine = engine # parts are passed in
self.wheels = wheels
def drive(self):
self.engine.start()
print(f"Rolling on {self.wheels.count} wheels")
car = Car(Engine(200), Wheels(4))
car.drive()
# Engine (200 hp) started
# Rolling on 4 wheels
Because the parts are passed in, you can swap them without changing Car:
sports_car = Car(Engine(600), Wheels(4))
trike = Car(Engine(30), Wheels(3))
Which should I use?
A good rule of thumb: favor composition over inheritance.
- Use inheritance when the "is-a" statement is truly natural and the child can fully stand in for the parent.
- Use composition when you just want to reuse behavior, or when the "is-a" sentence sounds wrong.
Bad inheritance: class Car(Engine). A car is not an engine!
Good composition: a Car has an Engine.
7. Getters and Setters (@property)
In some languages you write getName() and setName() methods for every attribute. In Python you start with a plain attribute, and only add control later if you need it, using @property.
The plain way
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Ana", 30)
p.age = -5 # nothing stops this
Adding validation with @property
class Person:
def __init__(self, name, age):
self.name = name
self.age = age # goes through the setter below!
@property
def age(self): # GETTER
return self._age
@age.setter
def age(self, value): # SETTER
if value < 0:
raise ValueError("Age cannot be negative")
self._age = value
p = Person("Ana", 30)
print(p.age) # 30 (calls the getter)
p.age = 31 # calls the setter
print(p.age) # 31
p.age = -5 # ValueError: Age cannot be negative
Notes:
- From the outside,
p.agestill looks like a normal attribute. No parentheses, noget_/set_. - The real value is stored in
self._age(with an underscore) so it doesn't clash with the property name. - The setter is also used inside
__init__, so bad values are caught right when the object is created.
Read-only and computed properties
If you define only a getter, the attribute is read-only. Properties are also great for values calculated on demand:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self): # computed each time, no setter
return self.width * self.height
r = Rectangle(3, 4)
print(r.area) # 12
r.width = 10
print(r.area) # 40 (always up to date)
r.area = 99 # AttributeError: can't set attribute
8. How Decorators Work
You've just seen @property and @age.setter. These are decorators. To understand them, you need three small ideas.
Idea 1: Functions are values
In Python, a function can be stored in a variable, passed as an argument, and returned from another function.
def shout(text):
return text.upper()
yell = shout # no parentheses: we're copying the function itself
print(yell("hi")) # HI
Idea 2: Functions can be defined inside functions
def outer():
def inner():
print("I'm inside!")
inner()
outer() # I'm inside!
Idea 3: A decorator takes a function and returns a new function
A decorator wraps a function to add behavior before and/or after it runs, without changing the function's own code.
# *args and **kwargs let the wrapper accept any arguments and passes them straight through to the original function.
def log_calls(func): # <- function as parameter
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}") # before running original func
result = func(*args, **kwargs) # run the original function
print(f"Finished {func.__name__}") # after running
return result
return wrapper
def add(a, b):
return a + b
add = log_calls(add) # manually "decorate" add
print(add(2, 3))
# Calling add
# Finished add
# 5
The @ syntax is a shortcut for exactly that last step:
@log_calls # same as: add = log_calls(add)
def add(a, b):
return a + b
print(add(2, 3))
# Calling add
# Finished add
# 5
Decorators you'll use with classes
@property= Makes a method behave like a read-only attribute (getter)@x.setter= Defines the setter for propertyx@staticmethod= A method that needs neitherselfnorcls. It's just a function living in the class@classmethod= A method that receives the class (cls) instead of an instance@abstractmethod= Marks a method that subclasses must implement
@classmethod and @staticmethod in action:
class Dog:
count = 0 # class attribute
def __init__(self, name):
self.name = name
Dog.count += 1
@classmethod
def from_string(cls, text): # alternative constructor
name = text.split(",")[0]
return cls(name) # same as Dog(name)
@staticmethod
def is_good_name(name): # doesn't use self or cls
return len(name) > 1
rex = Dog.from_string("Rex,3")
print(rex.name) # Rex
print(Dog.count) # 1
print(Dog.is_good_name("R")) # False
9. Quick Reference
class Example:
class_attr = "shared by all" # class attribute
def __init__(self, value): # constructor
self.value = value # instance attribute
def __str__(self): # friendly text: print(obj)
return f"Example({self.value})"
def __repr__(self): # developer text: repr(obj)
return f"Example(value={self.value!r})"
@property # getter
def value(self):
return self._value
@value.setter # setter
def value(self, new):
self._value = new
@classmethod # gets the class
def make_default(cls):
return cls(0)
@staticmethod # gets nothing extra
def helper():
return "I don't need self"
Summary List
- Class = Blueprint for objects
- Object =One concrete instance of a class
__init__= Constructor; sets up a new objectself= The current object- Class attribute = Shared by all instances
- Instance attribute = Unique to each instance
- Encapsulation = Bundle data + methods; guard the data
- Abstraction = Expose what it does, hide how
- Inheritance = "is-a": child reuses/extends parent
- Polymorphism = Same method name, different behavior per class
- Composition = "has-a": build objects out of other objects
@property= Getter/setter that looks like a plain attribute- Decorator = A function that wraps another function to add behavior
Practice Ideas
- Create a
Bookclass withtitle,author, andpages. Add__str__and__repr__. - Make
pagesa property that rejects values below 1. - Build a
Libraryclass that contains a list ofBookobjects (composition) and hasadd_bookandfind_by_authormethods. - Build a
Shapeabstract class withSquare,Triangle, andCirclesubclasses, and loop over a list of them callingarea(), make sure to implement the correct area formula for eachShape. - Write a
@log_callsdecorator and apply it to a few functions.
Comments