Project Brief
Let’s start the week by practicing object-oriented programming. This is a great exercise for everyone no matter what your Python specialization is. Today’s project and especially the elaborated solution in the link at the bottom will give you deep insights into how object-oriented programming works in Python. Your task is to rewrite some into object-oriented programming (OOP) style.
Step-By-Step Instructions
Take a look at the following code:
import random # Function to generate a random password def generate_password(length): characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()" password = ''.join(random.choice(characters) for i in range(length)) return password # Function to check password strength def check_password_strength(password): # Define criteria for a strong password criteria = { 'length': len(password) >= 8, 'lowercase': any(char.islower() for char in password), 'uppercase': any(char.isupper() for char in password), 'digit': any(char.isdigit() for char in password), 'special': any(char in "!@#$%^&*()" for char in password) } # Count how many criteria are met strength = sum(criteria.values()) return strength # Generate and print a random password of length 12 password = generate_password(12) print("Generated password:", password) # Check the strength of the generated password strength = check_password_strength(password) print("Password strength:", strength)
The code outputs this:
So, the script generates a random password and indicates its strength.
As you can see, the code uses the functional programming paradigm (i.e., functions). Your task is to rewrite the code using classes/OOP instead of functions.
Note that there are multiple correct ways to rewrite the code in OOP style. The solution in the button below covers two different versions of OOP code and it includes the pros and cons of each version. That will give you deep insights about how OOP works.
Environment Setup Instructions
You don’t need to install any library for this project.
Run the app with python main.py
Resources
Below you will find a beginner’s tutorial on classes that uses an example of a Student and a Course class to explain classes and OOP from a real-use case example:
https://pythonhow.com/what/classes-and-oop-in-python/
Project Solution
View, run, and play around with the code using the button below, even from your mobile phone.
Feel free to post your questions or comments in the comment section below.
Happy Coding!
Daily Python Projects Team