Object Oriented Programming
Object Oriented Programming
What is a Class?
Creating a Class
python
class Dog:
# Class attribute
Family = "German Shepherd"
# 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:
python
4. Initializer (Constructor):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
def get_age(self):
return self.age
Creating an Object
You can access the attributes and methods of an object using the
dot . notation:
class Dog:
Family = “German Shepherd”
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)
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
Example:
python
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
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
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
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)