Object-Oriented Programming in Python
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 316 wordsExplore the principles of object-oriented programming (OOP) in Python, including classes, inheritance, and polymorphism.
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure code. This guide covers the basics of OOP in Python, including classes, inheritance, and polymorphism.
A class is a blueprint for creating objects.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")
# Creating an instance
my_dog = Dog("Buddy", 3)
my_dog.bark() # Output: Buddy says Woof!
Methods are functions defined within a class, and attributes are variables that belong to the class.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")
def get_age(self):
return self.age
my_dog = Dog("Buddy", 3)
print(my_dog.get_age()) # Output: 3
Inheritance allows a class to inherit attributes and methods from another class.
class Animal:
def __init__(self, species):
self.species = species
def make_sound(self):
print("Sound!")
class Dog(Animal):
def __init__(self, name, age):
super().__init__("Dog")
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy", 3)
my_dog.bark() # Output: Buddy says Woof!
Inheritance promotes code reuse and can be used to create complex hierarchies.
class Cat(Animal):
def __init__(self, name, age):
super().__init__("Cat")
self.name = name
self.age = age
def meow(self):
print(f"{self.name} says Meow!")
my_cat = Cat("Whiskers", 2)
my_cat.meow() # Output: Whiskers says Meow!
Polymorphism allows different classes to be treated as instances of the same class through inheritance.
class Cat(Animal):
def make_sound(self):
print("Meow!")
def animal_sound(animal):
animal.make_sound()
dog = Dog("Buddy", 3)
cat = Cat("Whiskers")
animal_sound(dog) # Output: Sound!
animal_sound(cat) # Output: Meow!
Polymorphism allows for flexibility and interchangeability in code.
animals = [Dog("Buddy", 3), Cat("Whiskers", 2)]
for animal in animals:
animal.make_sound()
# Output:
# Buddy says Woof!
# Whiskers says Meow!
Understanding OOP principles is crucial for writing organized and scalable Python code. Practice creating classes and using inheritance and polymorphism to build complex applications.