⬅ Previous TopicPython Custom Exceptions
Next Topic ⮕Python Inheritance










Python OOPs
Object-Oriented Programming
When writing programs, we often deal with real-world things like students, cars, or bank accounts. These things have data (like a student's name or a car's color) and actions (like driving a car or updating a bank balance).
Object-Oriented Programming (OOP) helps us model these things in code using objects and classes.
Let’s See a Simple Example
Imagine you want to create a Dog. Every dog has a name and can bark. name is the attribute of a dog, while barking is its behaviour(method).
# Defining a class
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name + " says Woof!")
# Creating objects
dog1 = Dog("Tommy")
dog2 = Dog("Buddy")
# Calling methods
dog1.bark()
dog2.bark()
Output
Tommy says Woof!
Buddy says Woof!
What’s Happening Here?
class Dog:
creates a class named Dog.__init__()
is a special method that runs when we create an object. It sets the dog’s name.self.name
stores the name of the dog.bark()
is a method that prints a message using the dog’s name.dog1 = Dog("Tommy")
creates a dog named Tommy.dog1.bark()
tells Tommy to bark!
Key Concepts Here
- Class: A blueprint or template for creating objects.
- Object: An actual thing created from the class.
- Attributes: Variables that belong to an object (like name, age).
- Methods: Functions that belong to an object (like bark(), run()).
Let’s Add Another Method
We’ll make our Dog learn a new trick: sit.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name + " says Woof!")
def sit(self):
print(self.name + " sits down.")
dog = Dog("Charlie")
dog.bark()
dog.sit()
Output
Charlie says Woof!
Charlie sits down.
Understanding self
self
is used to refer to the current object. It lets each object keep its own data separate from other objects.
Why Do We Need OOP?
- Organized code: OOP keeps related code (data + actions) together.
- Reusability: You can reuse classes to create many similar objects.
- Easy to manage: Large projects are easier to understand and maintain.