0% found this document useful (0 votes)
0 views

Object Oriented Programming

Uploaded by

Akshat Joshi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Object Oriented Programming

Uploaded by

Akshat Joshi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Object-Oriented Programming (OOP)

What is a Class?

A class in Python is a blueprint for creating objects. Classes


encapsulate data and the functions that operate on that data into
a single unit. They help in organizing code and creating reusable
code structures.

Creating a Class

Here's a basic example of how to define a class in Python:

python
class Dog:
# Class attribute
Family = "German Shepherd"

# Initializer / Instance attributes


def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute

# Instance method
def bark(self):
return f"{self.name} says Woof!"
# Another instance method
def get_age(self):
return self.age

Explanation:

1. Class Definition:

python

class Dog:

o This line defines a new class named Dog.


2. Class Attribute:

python

3. Family = "German Shepherd"

Fmaily is a class attribute shared by all instances of the Dog


class. It is defined directly within the class body.

4. Initializer (Constructor):

def __init__(self, name, age):


self.name = name
self.age = age

o The __init__ method is a special method called a


constructor. It initializes instance attributes name and
age for a new object. The self keyword refers to the
instance itself.
5. Instance Attribute:

self.name = name
self.age = age

o self.name and self.age are instance attributes, unique to


each instance of the class. They are initialized by the
constructor.
6. Instance Method:

def bark(self):
return f"{self.name} says Woof!"

obark is an instance method. It operates on the instance


attributes and typically uses the self keyword to access
them.
7. Another Instance Method:

def get_age(self):
return self.age

o get_age is another instance method that returns the age


of the dog.

Creating an Object

To create an object of the class Dog, you instantiate the class:

# Create instances (objects) of the Dog class


dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)

Accessing Attributes and Methods

You can access the attributes and methods of an object using the
dot . notation:

# Access class attribute


print(dog1.Family) # Output: “German Shepherd”

# Access instance attributes


print(dog1.name) # Output: Buddy
print(dog1.age) # Output: 3

# Call instance methods


print(dog1.bark()) # Output: Buddy says Woof!
print(dog2.get_age()) # Output: 5
Full Example:

class Dog:
Family = “German Shepherd”

def __init__(self, name, age):


self.name = name
self.age = age

def bark(self):
return f"{self.name} says Woof!"

def get_age(self):
return self.age

# Create instances
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)

# Access attributes and methods


print(dog1.Family) # Output: “German Shepherd”
print(dog1.name) # Output: Buddy
print(dog1.age) # Output: 3
print(dog1.bark()) # Output: Buddy says Woof!
print(dog2.get_age())

Object-Oriented Programming (OOP) is a programming paradigm


that uses objects and classes to structure code in a way that is
modular, reusable, and easier to manage. The four main principles
or pillars of OOP are:
1. Abstraction

Abstraction involves hiding the complex implementation details


of a system and showing only the necessary features. It helps in
reducing complexity and allows focusing on what an object does
rather than how it does it.

Example:

python
class Vehicle:
def start_engine(self):
raise NotImplementedError("Subclass must implement
abstract method")

class Car(Vehicle):
def start_engine(self):
return "Car engine started"

class Motorcycle(Vehicle):
def start_engine(self):
return "Motorcycle engine started"

# Using abstraction
car = Car()
motorcycle = Motorcycle()
print(car.start_engine()) # Output: Car engine started
print(motorcycle.start_engine()) # Output: Motorcycle engine
started

2. Encapsulation

Encapsulation is the practice of bundling the data (attributes) and


the methods (functions) that manipulate the data into a single
unit, or class. It restricts access to the inner workings of that class
and prevents external code from directly accessing or modifying
internal data.

Example:
python
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute

def deposit(self, amount):


self.__balance += amount

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount
else:
return "Insufficient funds"

def get_balance(self):
return self.__balance

# Using encapsulation
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
print(account.withdraw(200)) # Output: None
print(account.get_balance()) # Output: 1300
print(account.withdraw(1500)) # Output: Insufficient funds
print(account.__balance) # This will raise an AttributeError

3. Inheritance

Inheritance allows a class to inherit the properties and methods


of another class. This helps in promoting code reuse and
establishing a relationship between the parent class and the child
class.

Example:

python
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

# Using inheritance
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(f"{dog.name} says {dog.speak()}") # Output: Buddy says
Woof!
print(f"{cat.name} says {cat.speak()}") # Output: Whiskers says
Meow!

4. Polymorphism

Polymorphism allows objects of different classes to be treated as


objects of a common superclass. It enables a single interface to be
used for different underlying forms (data types). This promotes
flexibility and maintainability in code.

Example:

python
class Bird:
def fly(self):
return "Flying"

class Plane:
def fly(self):
return "Flying with engines"
# Polymorphic function
def let_it_fly(flying_object):
print(flying_object.fly())

# Using polymorphism
sparrow = Bird()
boeing = Plane()
let_it_fly(sparrow) # Output: Flying
let_it_fly(boeing)

You might also like