Lesson 13: Python Classes and Object-Oriented Programming (OOP) | Coding Class Series
Introduction
Welcome to Lesson 13!
In this lesson, we will learn about Object-Oriented Programming (OOP) in Python, including classes, objects, methods, and inheritance.
OOP helps you structure your code in a way that models real-world objects and makes programming more organized and reusable.
1. What is a Class?
A class is a blueprint for creating objects. It defines attributes (data) and methods (functions).
# Define a class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says Woof!")
2. Creating Objects
An object is an instance of a class.
# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
print(dog1.name) # Buddy
dog2.bark() # Max says Woof!
3. The __init__ Method
__init__is a constructor used to initialize objects.selfrefers to the instance of the class.
class Cat:
def __init__(self, name, color):
self.name = name
self.color = color
def meow(self):
print(f"{self.name}, the {self.color} cat, says Meow!")
4. Methods
Methods are functions inside classes that operate on objects.
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.1416 * self.radius ** 2
def perimeter(self):
return 2 * 3.1416 * self.radius
c = Circle(5)
print(c.area()) # 78.54
print(c.perimeter()) # 31.416
5. Inheritance
Inheritance allows a class to inherit attributes and methods from another class.
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof Woof")
class Cat(Animal):
def speak(self):
print("Meow Meow")
d = Dog()
c = Cat()
d.speak() # Woof Woof
c.speak() # Meow Meow
6. Encapsulation
Encapsulation hides data inside a class using private attributes.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private variable
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
7. Polymorphism
Polymorphism allows objects of different classes to be used interchangeably.
class Bird:
def speak(self):
print("Tweet")
class Dog:
def speak(self):
print("Woof")
def make_speak(animal):
animal.speak()
b = Bird()
d = Dog()
make_speak(b) # Tweet
make_speak(d) # Woof
8. Practice Exercises
- Create a class
Studentwith attributesname,roll_no,marks. Write a method to calculate percentage. - Create a class
Vehicleand inherit it withCarandBike. Add different methods to each. - Implement encapsulation for a
Libraryclass wherebooksis private. - Write a program demonstrating polymorphism with two different classes.
No comments:
Post a Comment