Python Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects, which
represent instances of real-world entities, and the interactions between these objects. Python is an object-
oriented programming language, and understanding the principles of OOP is crucial for effective Python
programming. Here's an introduction to the key concepts of OOP in Python:
1. Classes and Objects:
Class: A class is a blueprint or template for creating objects. It defines attributes (data members) and
methods (functions) that the objects will have.
Object: An object is an instance of a class. It is a concrete entity created from the class, possessing the
attributes and behaviors defined in the class.
python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")
2. Attributes and Methods:
Attributes: These are variables that store data. In the above example, `name` and `age` are attributes.
Methods: These are functions defined within a class. The `bark` function in the example is a method.
3. Constructor (`__init__` method):
- The `__init__` method initializes the attributes of an object when it is created.
4. Inheritance:
Inheritance allows a class to inherit attributes and methods from another class. The new class is called a
subclass or derived class, and the existing class is the base class or parent class.
python
class Bulldog(Dog):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def bark(self): # Overriding the bark method
print(f"{self.name} (Bulldog) says Woof!")
5. Encapsulation:
- Encapsulation is the bundling of data (attributes) and methods that operate on the data into a single
unit (a class). It hides the internal details of how an object works.
6. Polymorphism:
- Polymorphism allows objects of different classes to be treated as objects of a common base class. It
allows methods to be used interchangeably for different data types.
python
def introduce_pet(pet):
print(f"I have a pet named {pet.name}.")
dog1 = Dog("Buddy", 3)
bulldog1 = Bulldog("Max", 2, "English Bulldog")
introduce_pet(dog1) # Outputs: I have a pet named Buddy.
introduce_pet(bulldog1) # Outputs: I have a pet named Max.
7. Abstraction:
- Abstraction involves simplifying complex systems by modeling classes based on real-world entities and
only exposing the essential features.