Object-Oriented Programming (OOP) in Python
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).
In this tutorial, you’ll learn about the core concepts of OOP in Python:
- Classes and Objects
- Inheritance
- Polymorphism
- Encapsulation
Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class.
Here’s how to define a simple class in Python:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")The __init__() method is a special method that’s called when you create a new object. It’s used to initialize the object’s attributes. The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
Now, let’s create a Dog object:
my_dog = Dog("Buddy", 3)
print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 3
my_dog.bark() # Output: Woof!Inheritance
Inheritance is the mechanism by which one class can inherit the attributes and methods of another class. The class that inherits is called the child class or subclass. The class that is inherited from is called the parent class or superclass.
Here’s an example of inheritance in Python:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"In this example, the Dog and Cat classes inherit from the Animal class. They both override the speak() method to provide their own implementation.
my_dog = Dog("Buddy")
print(my_dog.speak()) # Output: Woof!
my_cat = Cat("Whiskers")
print(my_cat.speak()) # Output: Meow!Polymorphism
Polymorphism is the ability of an object to take on many forms. In Python, polymorphism allows you to use a single interface to represent different types of objects.
For example, you can write a function that takes an Animal object as an argument, and it will work with both Dog and Cat objects:
def make_animal_speak(animal):
print(animal.speak())
make_animal_speak(my_dog) # Output: Woof!
make_animal_speak(my_cat) # Output: Meow!Encapsulation
Encapsulation is the bundling of data and methods that operate on that data into a single unit, or object. It’s used to restrict access to some of an object’s components, which can prevent the accidental modification of data.
In Python, you can use private attributes to achieve encapsulation. Private attributes are attributes that can only be accessed from within the class. You can define a private attribute by prefixing its name with two underscores (__).
class Car:
def __init__(self, make, model):
self.make = make
self.__fuel_level = 100
def drive(self):
if self.__fuel_level > 0:
self.__fuel_level -= 10
print("Driving...")
else:
print("Out of fuel!")
def get_fuel_level(self):
return self.__fuel_levelIn this example, the __fuel_level attribute is private. It can only be accessed from within the Car class.
my_car = Car("Honda", "Civic")
# This will cause an error
# print(my_car.__fuel_level)
# You can access the private attribute through a public method
print(my_car.get_fuel_level()) # Output: 100
my_car.drive() # Output: Driving...
print(my_car.get_fuel_level()) # Output: 90For more in-depth information on Object-Oriented Programming in Python, you can refer to the official Python documentation: https://docs.python.org/3/tutorial/classes.html