Table of contents
The Layout >
In Python, there are two ways to write programs :
Procedural Programming and Object-Oriented Programming (OOP).
OOP is a way of organizing code that makes it easier to write complex programs.
In OOP, you create classes that represent real-world things. A class is like a blueprint for an object. It defines what properties and methods the object will have. Properties are the data that the object will store, and methods are the things that the object can do.
For example, you could create a class called "Person" that has properties like name and age, and methods like speak() and walk(). Each instance of the Person class would be a unique object with its own name and age, but they would all have the same methods to speak and walk.
Here's another example :
You have a class called Animal.
Animals have properties like name, color, and size.
Animals can do things like eat, sleep, and run.
You can create different objects of the Animal class, like a dog, a cat, or a bird.
Each object will have its own unique properties and behaviors.
Example Code >
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def speak(self):
print(f"I am {self.name} the {self.species}.")
class Dog(Animal):
def wag_tail(self):
print(f"{self.name} is wagging its tail.")
class Cat(Animal):
def purr(self):
print(f"{self.name} is purring.")
if __name__ == "__main__":
dog = Dog("Spot", "Labrador Retriever")
dog.speak()
dog.wag_tail()
cat = Cat("Garfield", "Tabby")
cat.speak()
cat.purr()
๐๐ป Try this and See the output !
Key Features >
OOP has a few key features that make it useful for writing complex programs.
- Encapsulation: Encapsulation means that the data inside an object is hidden from the outside world. This makes it more difficult for the data to be accidentally modified.
class Person:
def __init__(self, name, age):
self.name = name
self._age = age # Private property
def get_name(self):
return self.name
def get_age(self):
return self._age
def set_age(self, new_age):
if new_age < 0:
raise ValueError("Age cannot be negative")
self._age = new_age
person = Person("John Doe", 20)
print(person.get_name()) # Prints "John Doe"
print(person.get_age()) # Prints 20
person.set_age(30)
print(person.get_age()) # Prints 30
๐๐ป Try this and See the output !
Inheritance: Another feature of OOP is inheritance. Inheritance allows you to create new classes that inherit the properties and methods of existing classes. This makes it easy to create new classes that have similar functionality to existing classes.
This is known as the base class or parent class.
The new class is called the derived class or child class.
Inheritance in Python is implemented using the
class
keyword. Theclass
keyword is used to define a new class, and theextends
keyword is used to specify the base class.For example, the following code defines a class called
Animal
and a derived class calledDog
:
class Animal:
def speak(self):
print("I am an animal.")
class Dog(Animal):
def bark(self):
print("Woof!")
๐๐ป Try this and See the output !
- Polymorphism: Polymorphism is the ability of an object to take on different forms. This is done by defining methods with the same name in different classes. When a method is called on an object, the correct method is executed depending on the type of object that is being called. This allows us to write code that is more generic and flexible.
class SchoolSubject:
def learn(self):
print(f"I am learning {self.name}.")
class Math(SchoolSubject):
def solve_equation(self, equation):
print(f"I solved the equation {equation}.")
class English(SchoolSubject):
def write_paragraph(self, topic):
print(f"I wrote a paragraph about {topic}.")
def main():
subject = SchoolSubject("Math", "The study of numbers and shapes.")
subject.learn()
subject = Math()
subject.solve_equation("2 + 2 = 4")
subject = English()
subject.write_paragraph("The importance of education.")
if __name__ == "__main__":
main()
๐๐ป Try this and See the output !
In summary, OOP is a powerful way to write complex programs. It allows you to model real-world things, reuse code, and write more flexible code.
In this post, we have explored the basics of Python OOP concepts. We have learned about objects, classes, inheritance, polymorphism, and encapsulation. These concepts are essential for understanding and using Python OOP effectively.
I hope this post has been helpful. If you have any questions, please feel free to leave a comment below.
Happy Coding !
Thank You