Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming
(OOP) is a programming paradigms that creates software by modeling real-world entities or concepts as objects
and enables these objects communicate with each other within a program.
Core Concepts of Object-Oriented Programming
Object-Oriented Programming involves managing data
(attributes) and functions that process the data (methods
) as a single object
.
The key concepts are as follows:
-
Object
: An object combinesdata
(attributes, Property) and the operations on the data (methods
, Method). For instance, a Car object can have properties like color, model, and speed (attributes) and methods like accelerate and stop (functions). -
Class
: A class is like the blueprint for a car, serving as adesign template
for creating objects. Classes define the attributes and methods that the objects created from them will share, and an object created from a class is called aninstance
. -
Inheritance
: Inheritance allows one class (child class) to inherit the properties and methods of another class (parent class). This enhances the reusability of code. -
Encapsulation
: Encapsulation refers to the practice of hiding an object'sdata (attributes)
from external access and manipulating data only through the object'smethods
. This ensures data protection and security. -
Polymorphism
: Polymorphism allows methods with the same name to have different implementations in different classes. This ensuring that the code is more flexible and reusable.
The relationship between a class and an object can be compared to a car blueprint and a car, or a recipe and a dish.
Example of OOP Usage
The following code defines an Animal
class and a Dog
class, which inherits from the Animal
class.
The Animal
class has a name
attribute and defines a speak
method.
The Dog
class inherits from the Animal
class and overrides the speak
method.
class Animal: # Define Animal class
def __init__(self, name): # Constructor method
self.name = name # Define name attribute
def speak(self): # Define speak method
pass
class Dog(Animal): # Define Dog class
def speak(self): # Override speak method
return f"{self.name} says woof!" # Use name attribute
# Create and use objects
my_dog = Dog("Buddy")
print(my_dog.speak())
# Output: Buddy says woof!
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.