Python OOP

🐍 Python OOP (Object-Oriented Programming) — Complete Guide

Python supports Object-Oriented Programming (OOP), a programming paradigm based on objects rather than functions and logic.

OOP helps in organizing code, making it reusable, scalable, and easier to maintain.


🔥 Key OOP Concepts in Python

Concept Meaning
Class A blueprint/template for creating objects
Object An instance of a class
Constructor A special method that initializes an object
Attributes Variables inside a class
Methods Functions inside a class
Inheritance One class can acquire properties of another
Encapsulation Restricting direct access to the data
Polymorphism Same method behaves differently based on object
Abstraction Hiding complex code and exposing only essential parts

1️⃣ Creating Class & Object

class Person:
name = "John"
age = 30

obj = Person()
print(obj.name)
print(obj.age)


2️⃣ The __init__() Constructor

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

p = Person("Alice", 25)
print(p.name)
print(p.age)


3️⃣ Class Attributes vs Instance Attributes

class Example:
count = 0 # class variable

def __init__(self, value):
self.value = value # instance variable

obj1 = Example(10)
obj2 = Example(20)

print(obj1.value, obj2.value)
print(obj1.count, obj2.count)


4️⃣ Methods in Classes

class Dog:
def bark(self):
print("Woof! Woof!")

dog = Dog()
dog.bark()


5️⃣ Inheritance

class Animal:
def sound(self):
print("Animal makes sound")

class Dog(Animal):
def sound(self):
print("Dog barks")

d = Dog()
d.sound()


6️⃣ Multiple Inheritance

class A:
def methodA(self):
print("Class A")

class B:
def methodB(self):
print("Class B")

class C(A, B):
pass

obj = C()
obj.methodA()
obj.methodB()


7️⃣ Polymorphism

class Bird:
def fly(self):
print("Bird can fly")

class Penguin(Bird):
def fly(self):
print("Penguin cannot fly")

b1 = Bird()
b2 = Penguin()

b1.fly()
b2.fly()


8️⃣ Encapsulation (Private Variables)

class Bank:
def __init__(self):
self.__balance = 1000 # private variable

def show_balance(self):
print(self.__balance)

b = Bank()
b.show_balance()


9️⃣ Abstraction (using ABC module)

from abc import ABC, abstractmethod

class Car(ABC):
@abstractmethod
def start(self):
pass

class Tesla(Car):
def start(self):
print("Tesla starts silently!")

t = Tesla()
t.start()


🔟 Static & Class Methods

class Utility:

@staticmethod
def add(a, b):
return a + b

@classmethod
def info(cls):
return "This is a class method"

print(Utility.add(4, 6))
print(Utility.info())


🎉 Benefits of OOP

  • Better code organization

  • Reusability through inheritance

  • Easier debugging & scaling

  • Secure & modular applications

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *