0
0
Pythonprogramming~5 mins

OOP principles overview in Python

Choose your learning style9 modes available
Introduction

OOP helps organize code by grouping related data and actions together. It makes programs easier to build, understand, and change.

When you want to model real-world things like cars, animals, or people in your program.
When your program has many parts that share similar features but also have differences.
When you want to reuse code without rewriting it again and again.
When you want to keep your code safe from accidental changes.
When you want to make your program easier to fix or add new features later.
Syntax
Python
class ClassName:
    def __init__(self, value):
        self.attribute = value

    def method(self):
        # action code here

class defines a new type or blueprint.

__init__ is a special method to set up new objects.

Examples
This defines a Dog class with a name and a bark action.
Python
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says Woof!")
Cat inherits from Animal, so it gets species and adds meow.
Python
class Animal:
    def __init__(self, species):
        self.species = species

class Cat(Animal):
    def meow(self):
        print("Meow!")
Sample Program

This program creates a Person with a name and age, then says hello.

Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Create a person object
p = Person("Alice", 30)
p.greet()
OutputSuccess
Important Notes

Encapsulation means keeping data safe inside objects.

Inheritance lets one class get features from another.

Polymorphism means different classes can use the same method name in their own way.

Abstraction hides complex details and shows only what is needed.

Summary

OOP groups data and actions into classes and objects.

Four main principles: Encapsulation, Inheritance, Polymorphism, Abstraction.

OOP helps write clear, reusable, and easy-to-change code.