Object-Oriented Programming:
Object-Oriented Programming is a programming paradigm that emphasizes the use of objects and classes to model real-world entities and concepts. Python is a powerful language for implementing OOP concepts, and it provides many built-in features to support OOP.
1. Classes and Objects:
In Python, a class is a blueprint for creating objects. A class defines a set of attributes and methods that are common to all objects of that class. Here’s an example of how to define a class in Python:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(“Woof!”)
In this example, we have defined a Dog
class that has two attributes (name
and breed
) and one method (bark
). The __init__
method is a special method that gets called when an object of the class is created. It initializes the object’s attributes with the values passed to it as arguments.
To create an object of the Dog
class, you can use the class name followed by parentheses:
my_dog = Dog(“Fido”, “Labrador”)
This creates a new Dog
object with the name “Fido” and the breed “Labrador”.
2. Accessing Object Attributes and Methods:
Once you have created an object of a class, you can access its attributes and methods using the dot notation:
print(my_dog.name) # Output: Fido
my_dog.bark() # Output: Woof!
This will print the name of the Dog
object and make it bark.
3. Inheritance:
Inheritance is a powerful feature of OOP that allows you to create a new class based on an existing class. The new class inherits all the attributes and methods of the existing class and can also add new attributes and methods of its own.
Here’s an example of how to define a Poodle
class that inherits from the Dog
class:
class Poodle(Dog):
def __init__(self, name):
super().__init__(name, “Poodle”)
def bark(self):
print(“Yip!”)
In this example, we have defined a Poodle
class that inherits from the Dog
class. It has a different bark method (Yip!
) and a different breed (Poodle
).
To create an object of the Poodle
class, you can use the same syntax as before:
my_poodle = Poodle(“Fluffy”)
This creates a new Poodle
object with the name “Fluffy”.
4. Polymorphism:
Polymorphism is another important feature of OOP that allows objects of different classes to be used interchangeably. In Python, polymorphism is achieved through method overriding, which allows a subclass to provide a different implementation of a method that is already defined in its superclass.
In the previous example, we overrode the bark()
method in the Poodle
class to make it bark differently than the Dog
class.