Day 7: Object-Oriented Programming (OOP) in Python – Python 30-Day Challenge ??
Welcome to Day 7 of my Python 30-Day Challenge! Today, I explored the basics of Object-Oriented Programming (OOP), one of the most powerful paradigms in Python. OOP helps in writing scalable, reusable, and organized code by structuring programs around objects and classes.
?? What I Learned Today
?? What is Object-Oriented Programming (OOP)?
OOP is a programming paradigm based on the concept of objects, which contain attributes (data) and methods (functions).
? Encapsulation – Bundling data and methods into a single unit (class). ? Abstraction – Hiding complex implementation details. ? Inheritance – Enabling new classes to derive properties from existing classes. ? Polymorphism – Allowing objects to be treated as instances of their parent class.
?? Classes & Objects in Python
A class is a blueprint for creating objects. An object is an instance of a class.
?? Creating a Class and an Object
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
# Creating an object (instance)
my_car = Car("Toyota", "Corolla", 2022)
print(my_car.brand) # Output: Toyota
print(my_car.model) # Output: Corolla
?? The __init__ Constructor
The __init__ method is a special constructor in Python that initializes object attributes.
?? Example: Defining a Constructor
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
print(person1.name) # Output: Alice
领英推荐
?? Methods in Classes
Methods are functions defined inside a class that operate on class attributes.
?? Example: Adding Methods to a Class
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def car_info(self):
return f"{self.year} {self.brand} {self.model}"
# Creating an object
my_car = Car("Tesla", "Model 3", 2023)
print(my_car.car_info()) # Output: 2023 Tesla Model 3
?? Exercise: Create a Car Class
? Define a Class with Attributes and Methods
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def display_info(self):
return f"Car: {self.year} {self.brand} {self.model}"
# Creating an instance of Car
car1 = Car("Ford", "Mustang", 2021)
print(car1.display_info())
?? Resources Used
Final Thoughts
OOP is a game-changer in Python, making programs modular, reusable, and maintainable. Understanding classes, objects, and methods is key to writing efficient, scalable code.
?? Next up: Inheritance & Polymorphism! Excited to explore more OOP concepts. Drop a comment if you have any questions or feedback! ??
#Python #Day7 #30DayChallenge #OOP #Coding #Programming #PythonForBeginners