// Object-oriented programming
OOP — The Full Picture
You've covered the full OOP landscape. Before moving on, here's everything in one place.
// Class and object
class Animal:
def __init__(self, name, species, age):
self.name = name # instance attribute
self.species = species
self.age = age
self.status = "available"
lassie = Animal("Lassie", "dog", 4) # object — instance of Animal
print(lassie.name) # Lassie
// self
def describe(self):
print(f"{self.name} is a {self.age} year old {self.species}.")
# self = the object the method is called on
# passed automatically — never manually
# self.attr accesses this object's own data
// Class attribute vs instance attribute
class Animal:
shelter = "Safe Paws" # class attribute — shared by all
def __init__(self, name):
self.name = name # instance attribute — unique per object
// Encapsulation
self._health = health # private by convention
self.__status = status # name-mangled
def get_health(self): return self._health
def set_health(self, h):
if h in ["healthy", "ill"]:
self._health = h
// Inheritance
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age) # runs Animal.__init__
self.breed = breed # Dog's own addition
print(isinstance(lassie, Dog)) # True
print(isinstance(lassie, Animal)) # True
// Polymorphism
for animal in shelter:
animal.describe() # Dog.describe() or Cat.describe()
# Python routes automatically — no isinstance() needed
// Special methods
def __str__(self): return f"{self.name} | {self.species}" # print()
def __repr__(self): return f"Animal('{self.name}')" # repr()
def __len__(self): return len(self.animals) # len()
def __eq__(self, other): return self.name == other.name # ==
def __contains__(self, item): return item in self.animals # in
// Common mistakes
# self.name = name ← correct
# name = name ← wrong — local variable only
# super().__init__() ← always call in child class
# def __init__(self, items=None):
# self.items = items if items is not None else []
# ← never use mutable defaults
# Always define __str__ — costs one method, saves every debug session
That's OOP. The cheatsheet above is yours to download and keep.
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment