⬅ Previous Topic
Python Exception HandlingNext Topic ⮕
Python Inheritance – Reusing Code the Easy Way⬅ Previous Topic
Python Exception HandlingNext Topic ⮕
Python Inheritance – Reusing Code the Easy WayWhen 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.
Imagine you want to create a Dog. Every dog has a name and can bark.
# 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()
Tommy says Woof!
Buddy says Woof!
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!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()
Charlie says Woof!
Charlie sits down.
self
self
is used to refer to the current object. It lets each object keep its own data separate from other objects.
Once you understand classes and objects, you can explore more OOP features:
Now that you’ve taken your first step into OOP, you're ready to explore how to use it to build real-world programs in Python!
⬅ Previous Topic
Python Exception HandlingNext Topic ⮕
Python Inheritance – Reusing Code the Easy WayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.