π§ Mastering Object-Oriented Programming (OOP) in Python: the basics
Object-Oriented Programming (OOP) is a foundational programming paradigm in Python. This all-in-one lesson is designed to give you a solid grasp of classes, objects, encapsulation, inheritance, and polymorphism in one practical, comprehensive session.
π― Lesson Objectives
- Understand what OOP is and why it’s useful.
- Learn to define and instantiate classes and objects.
- Explore constructors, attributes, and methods.
- Apply encapsulation to protect internal state.
- Use inheritance to extend functionality.
- Implement polymorphism to write flexible code.
- See how OOP principles apply to test automation.
π What is Object-Oriented Programming?
OOP is a paradigm where we structure programs around “objects”βbundles of related data and functionality. Each object is an instance of a class, which acts like a blueprint.
Why OOP?
- Improves modularity
- Enhances code reuse
- Makes maintenance easier
- Enables abstraction and data hiding
π§± Defining Classes and Creating Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
# Creating an object
p1 = Person("Alice", 30)
print(p1.greet())
π Encapsulation
Encapsulation means restricting direct access to some of an object’s components.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
Use single underscore _
for protected members and double underscore __
for private members.
ποΈ Inheritance
Inheritance allows one class (child) to inherit the attributes and methods of another (parent).
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof"
pet = Dog()
print(pet.speak()) # Woof
π Polymorphism
Polymorphism allows the same interface to behave differently depending on the object.
class Cat:
def sound(self):
return "Meow"
class Dog:
def sound(self):
return "Bark"
def animal_sound(animal):
print(animal.sound())
animal_sound(Cat()) # Meow
animal_sound(Dog()) # Bark
π§ͺ Final Project: Library System
Combine all concepts into a mini project:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
class Member:
def __init__(self, name):
self.name = name
self.books = []
def borrow_book(self, book):
self.books.append(book)
def list_books(self):
return [book.title for book in self.books]
book1 = Book("1984", "George Orwell")
book2 = Book("Python 101", "John Doe")
m = Member("Alice")
m.borrow_book(book1)
m.borrow_book(book2)
print(m.list_books()) # ['1984', 'Python 101']
π§ͺ Application of OOP in Test Automation
Object-Oriented Programming is extremely useful in test automation, particularly with frameworks like unittest
, pytest
, and Selenium
.
Benefits:
- Test Case Organization: Each test scenario can be encapsulated in a class.
- Reusable Components: Page Object Model (POM) uses classes to represent pages, with methods as interactions.
- Maintainability: Changing logic in one place updates all affected tests.
Example: Using POM with Selenium
class LoginPage:
def __init__(self, driver):
self.driver = driver
def enter_username(self, username):
self.driver.find_element("id", "username").send_keys(username)
def enter_password(self, password):
self.driver.find_element("id", "password").send_keys(password)
def click_login(self):
self.driver.find_element("id", "login").click()
# In your test file:
login_page = LoginPage(driver)
login_page.enter_username("testuser")
login_page.enter_password("password123")
login_page.click_login()
Practice yourself with the Google Colab examples:
π Colab Example
Or go to my GitHub examples repository to find the object oriented examples:
π Operators-Condition Examples
π Summary: The 4 Pillars of OOP
Concept | Description |
---|---|
Encapsulation | Hide internal state, expose behavior via methods |
Abstraction | Simplify complexity using meaningful classes |
Inheritance | Share and override functionality |
Polymorphism | Use one interface for many implementations |
Congratulations! π You’ve completed a crash course in OOP with Python. Practice regularly to reinforce your skills and explore more complex use cases!