Table of Contents
Introdution:
Object-oriented programming (OOP) is a programming paradigm that uses objects, which are instances of classes, to organize code. Here are some basic concepts of OOP in Python:
Object-oriented programming (OOP) is a programming paradigm that uses objects, which are instances of classes, to organize code. Here are some basic concepts of OOP in Python:
1. Class
A class is a blueprint for creating objects. It defines a data structure that represents a real-world entity and the methods (functions) that operate on that data. Here’s a simple example of a class in Python:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
# Creating an instance of the Dog class
my_dog = Dog("Buddy", 3)
# Accessing attributes
print(my_dog.name) # Output: Buddy
# Calling a method
my_dog.bark() # Output: Woof!
2. Object
An object is an instance of a class. It is a concrete realization of the class blueprint, with its own unique data and behavior. In the example above, my_dog is an object of the Dog class.
3. Attributes:
Attributes are variables that store data within a class. In the Dog class example, name and age are attributes.
4. Methods
Methods are functions defined within a class. They represent the behavior associated with the objects of the class. In the Dog class example, init is a special method called the constructor, and bark is a custom method.
5. Encapsulation:
Encapsulation refers to the bundling of data (attributes) and methods that operate on the data within a single unit (class). It helps in hiding the internal details of an object and only exposing what is necessary.
6. Inheritance:
Inheritance allows a class (subclass/derived class) to inherit attributes and methods from another class (superclass/base class). It promotes code reuse and supports the creation of a hierarchy of classes.
class GoldenRetriever(Dog):
def fetch(self):
print("Fetching the ball!")
my_golden = GoldenRetriever("Max", 2)
my_golden.bark() # Output: Woof!
my_golden.fetch() # Output: Fetching the ball!
7. Polymorphism:
Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables a single interface to represent different types of objects.
def introduce_pet(pet):
print(f"My pet {pet.name} is {pet.age} years old.")
introduce_pet(my_dog) # Output: My pet Buddy is 3 years old.
introduce_pet(my_golden) # Output: My pet Max is 2 years old.
Conclusion:
These are some fundamental concepts of OOP in Python. Understanding and applying these concepts can help you write more organized, modular, and reusable code.