Lesson 19: Python Classes, Objects, and OOP | Coding Class Series
Introduction
Welcome to Lesson 19!
In this lesson, we will learn about Object-Oriented Programming (OOP) in Python, including classes, objects, attributes, and methods.
OOP helps in writing organized, reusable, and modular code.
1. What is a Class?
A class is a blueprint for creating objects.
It defines attributes (data) and methods (functions) that the objects will have.
Example:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")
2. Creating Objects
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name) # Output: Buddy
print(my_dog.breed) # Output: Golden Retriever
my_dog.bark() # Output: Buddy says Woof!
3. Instance vs Class Attributes
- Instance attributes – unique for each object
- Class attributes – shared by all objects
Example:
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name, breed):
self.name = name # instance attribute
self.breed = breed
dog1 = Dog("Buddy", "Golden Retriever")
dog2 = Dog("Max", "Beagle")
print(dog1.species) # Canis familiaris
print(dog2.species) # Canis familiaris
4. Methods
Methods are functions inside classes:
- Instance methods – operate on instance data
- Class methods – operate on class data
- Static methods – utility methods that don’t access class or instance data
Example:
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
def area(self):
return Circle.pi * self.radius ** 2
c = Circle(5)
print(c.area()) # Output: 78.53975
5. Inheritance
Inheritance allows a class to use attributes and methods of another class.
Example:
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
def bark(self):
print("Woof!")
dog = Dog()
dog.eat() # Eating
dog.bark() # Woof!
6. Practice Exercises
- Create a class
Carwith attributesmake,model, andyear, and a method to display info. - Create two objects of
Carand print their details. - Add a class method to count the number of cars created.
- Implement inheritance with a
Truckclass derived fromCarwith an extra methodload_cargo.
No comments:
Post a Comment