Object-Oriented Programming Basics
Duration: 5 min
What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a programming paradigm based on objects and classes. Instead of thinking about programs as sequences of commands, OOP thinks about them as collections of objects that interact with each other. This approach makes code more modular, reusable, and easier to maintain.
Classes and Objects
A class is a blueprint for creating objects. It defines the structure (attributes) and behavior (methods) that objects of that class will have. An object is an instance of a class - a concrete realization of the blueprint.
# Define a class
class Dog:
# Constructor - initializes the object
def __init__(self, name, breed):
self.name = name
self.breed = breed
# Methods
def bark(self):
return f"{self.name} says: Woof!"
def describe(self):
return f"{self.name} is a {self.breed}"
# Create objects (instances)
dog1 = Dog("Buddy", "Golden Retriever")
dog2 = Dog("Max", "Labrador")
# Call methods
print(dog1.bark())
print(dog1.describe())
print(dog2.describe())Buddy says: Woof!
Buddy is a Golden Retriever
Max is a LabradorAttributes and Methods
class Person:
def __init__(self, name, age):
self.name = name # Attribute
self.age = age # Attribute
def greet(self): # Method
return f"Hello, I'm {self.name}"
def have_birthday(self): # Method
self.age += 1
return f"{self.name} is now {self.age} years old"
person = Person("Alice", 25)
print(person.greet())
print(person.have_birthday())
print(f"Age: {person.age}")Hello, I'm Alice
Alice is now 26 years old
Age: 26Inheritance
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
return f"{self.name} is eating"
# Child class
class Cat(Animal):
def meow(self):
return f"{self.name} says: Meow!"
# Create object
cat = Cat("Whiskers")
print(cat.eat()) # Inherited method
print(cat.meow()) # Own methodWhiskers is eating
Whiskers says: Meow!Method Overriding
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.speak())
print(cat.speak())Woof!
Meow!💡 Tip: The init method is called automatically when you create an object. It's used to initialize the object's attributes.
Learn more: https://docs.python.org/3/tutorial/classes.html
❓ What is the purpose of the __init__ method?