Python FunctionsPython Functions1

Python Exception HandlingPython Exception Handling1

🔍

Python OOPs (Object-Oriented Programming) Introduction for Beginners



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.

Why Do We Need OOP?

Key Concepts of OOP in Python

Let’s See a Simple Example

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()

Output

Tommy says Woof!
Buddy says Woof!

What’s Happening Here?

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 the Magic Word self

self is used to refer to the current object. It lets each object keep its own data separate from other objects.

What’s Next in OOP?

Once you understand classes and objects, you can explore more OOP features:

Summary

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!



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You 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.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M