0% found this document useful (0 votes)
3 views3 pages

OOPs Concepts Python Modern

Uploaded by

chennujaswanth7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

OOPs Concepts Python Modern

Uploaded by

chennujaswanth7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

OOPs Concepts in Python

1. Class and Object

Class is a blueprint for creating objects. Object is an instance of a class.

class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

my_car = Car("Toyota", "Corolla")


print(my_car.brand) # Output: Toyota

2. Encapsulation

Encapsulation restricts access to certain details of an object.

class BankAccount:
def __init__(self, balance):
self.__balance = balance

def get_balance(self):
return self.__balance

account = BankAccount(1000)
print(account.get_balance()) # Output: 1000

3. Inheritance

Inheritance allows one class to inherit properties and methods of another.

class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def speak(self):
print("Dog barks")
OOPs Concepts in Python

d = Dog()
d.speak() # Output: Dog barks

4. Polymorphism

Polymorphism allows the same method to have different behaviors in different classes.

class Cat:
def sound(self):
print("Meow")

class Dog:
def sound(self):
print("Bark")

def make_sound(animal):
animal.sound()

make_sound(Cat()) # Output: Meow


make_sound(Dog()) # Output: Bark

5. Abstraction

Abstraction hides internal details and shows only the necessary features.

from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

class Circle(Shape):
def __init__(self, radius):
self.radius = radius
OOPs Concepts in Python

def area(self):
return 3.14 * self.radius ** 2

c = Circle(5)
print(c.area()) # Output: 78.5

Bonus: Constructor & Destructor

Constructor (__init__) is called on object creation. Destructor (__del__) is called on object deletion.

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

def __del__(self):
print("Object destroyed")

p = Person("Bob")
del p # Output: Object destroyed

You might also like