Lab 7: Object-Oriented Programming - Detailed Solutions
This document provides detailed explanations for Lab 7 solutions, focusing on object-oriented programming in Python.
Question 1: Rectangle Class
Task: Write a Python program to create a class named rectangle with attributes for width and height, methods for initialization and area
calculation, and use the class to calculate the area of a rectangle with user-provided dimensions.
1 # Create a class to represent a rectangle with width and height attributes
2 class rectangle:
3 def __init__(self, width, height): # Constructor that initializes new rectangle objects 1
4 self.width = width # Store the width parameter as an instance attribute
5 self.height = height # Store the height parameter as an instance attribute
6
7 def area(self): # Method to calculate the rectangle's area
8 return self.width * self.height # Calculate and return area (width × height)
9
10 # Get input from user for rectangle dimensions
11 width = float(input("Enter width: ")) # Get width from user and convert to float
12 height = float(input("Enter height: ")) # Get height from user and convert to float
13
14 # Create an instance of the rectangle class with user-provided dimensions
15 rect1 = rectangle(width, height) # Create a new rectangle object
16
17 # Calculate and display the area of the rectangle
18 print(rect1.area()) # Call the area method and print the result
Explanation:
• Line 2: Define a class named rectangle that will serve as a blueprint for rectangle objects.
• Line 3: Define the special __init__ method (constructor) that is automatically called when a new object is created. It takes three
parameters:
o self: A reference to the current instance of the class (automatically provided)
o width: The width of the rectangle
o height: The height of the rectangle
• Lines 4-5: Initialize the object's attributes by assigning the parameter values to the instance variables.
• Line 7: Define a method named area that calculates the area of the rectangle.
• Line 8: Return the area by multiplying the width and height attributes of the instance.
• Lines 11-12: Get the width and height values from the user and convert them to floating-point numbers.
• Line 15: Create a new instance of the rectangle class named rect1, passing the user-provided width and height as arguments.
• Line 18: Call the area method on the rect1 object and print the result.
2
Question 2: Vector2D Class
Task: Write a Python program to create a class named vector2D with attributes for x and y coordinates, methods for initialization, addition,
and subtraction, and use the class to perform vector operations.
1 class vector2D: # Define a class to represent 2D vectors
2 def __init__(self, x, y): # Constructor to initialize vector coordinates
3 self.x = x # Store the x-coordinate as an instance attribute
4 self.y = y # Store the y-coordinate as an instance attribute
5
6 def add(self, vector): # Method to add this vector with another vector
7 x_add = self.x + vector.x # Add x-coordinates
8
9
y_add = self.y + vector.y # Add y-coordinates
return x_add, y_add # Return the sum as a tuple (x, y) 3
10
11 def sub(self, vector): # Method to subtract another vector from this vector
12 x_sub = self.x - vector.x # Subtract x-coordinates
13 y_sub = self.y - vector.y # Subtract y-coordinates
14 return x_sub, y_sub # Return the difference as a tuple (x, y)
15
16 # Create two vector objects with specific coordinates
17 v1 = vector2D(5, 7) # Create first vector with coordinates (5, 7)
18 v2 = vector2D(3, 9) # Create second vector with coordinates (3, 9)
19
20 # Display the coordinates of both vectors
21 print("First vector:", v1.x, " ", v1.y) # Print first vector's coordinates
22 print("Second vector:", v2.x, " ", v2.y) # Print second vector's coordinates
23
24 # Add the vectors and display the x and y components of the result
25 print("Result of adding x:", v1.add(v2)[0]) # Display the x-component of v1 + v2
26 print("Result of adding y:", v1.add(v2)[1]) # Display the y-component of v1 + v2
27
28 # Subtract the vectors and display the x and y components of the result
29 print("Result of subtracting x:", v1.sub(v2)[0]) # Display the x-component of v1 - v2
30 print("Result of subtracting y:", v1.sub(v2)[1]) # Display the y-component of v1 - v2
Explanation:
• Line 1: Define a class named vector2D to represent two-dimensional vectors.
• Line 2: Define the __init__ method that takes x and y coordinates as parameters.
• Lines 3-4: Initialize the object's attributes with the provided x and y values.
• Line 6: Define an add method that takes another vector as a parameter.
• Lines 7-8: Calculate the sum of x and y coordinates of the two vectors.
•
•
Line 9: Return a tuple containing the x and y components of the sum.
Line 11: Define a sub method that takes another vector as a parameter.
4
• Lines 12-13: Calculate the difference of x and y coordinates of the two vectors.
• Line 14: Return a tuple containing the x and y components of the difference.
• Lines 17-18: Create two vector objects with specific coordinates.
• Lines 21-22: Print the x and y components of both vectors.
• Lines 25-26: Call the add method on v1 with v2 as an argument, and print the x and y components of the result. The [0] and [1] are
used to access the first and second elements of the returned tuple.
• Lines 29-30: Call the sub method on v1 with v2 as an argument, and print the x and y components of the result.
Question 3: BankAccount Class (Homework)
Task: Write a Python program to create a class named BankAccount with attributes for account ID, holder name, and balance, methods for
deposit, withdrawal, display, and fee calculation, and use the class to manage a bank account.
1 class BankAccount: # Define a class to represent a bank account
2 def __init__(self, id, name, balance): # Constructor to initialize account details
3 self.id = id # Store the account ID as an instance attribute
4 self.name = name # Store the account holder's name
5 self.balance = balance # Store the initial account balance
6 print("Welcome to your bank account!") # Display welcome message when account is created
7
8
9
def deposit(self): # Method to add money to the account
addB = float(input("Enter amount to deposit:")) # Get deposit amount from user 5
10 self.balance += addB # Add deposit amount to current balance
11 # self.balance = self.balance + addB # Alternative way to add to balance
12 print("Deposit successful!") # Display success message
13 print("New balance:", self.balance) # Display updated balance
14
15 def withdraw(self): # Method to remove money from the account
16 subB = float(input("Enter amount to withdraw:")) # Get withdrawal amount from user
17 if subB > self.balance: # Check if withdrawal amount exceeds balance
18 print("Insufficient funds") # Display error message if insufficient funds
19 else: # If sufficient funds are available
20 self.balance -= subB # Subtract withdrawal amount from balance
21 print("Withdraw successful!") # Display success message
22 print("New balance:", self.balance) # Display updated balance
23
24 def display(self): # Method to show account information
25 print("ID:", self.id) # Display account ID
26 print("Name", self.name) # Display account holder's name
27 print("Balance:", self.balance) # Display current balance
28
29 def bankfees(self): # Method to calculate balance after bank fees
30 return self.balance * 0.95 # Return 95% of balance (after 5% fee deduction)
31
32 # Create a bank account object with specific details
33 account1 = BankAccount(245444422, "Ali", 22300) # Create account with ID, name and balance
34
35 # Test the account methods
36 account1.display() # Show account information
37 account1.deposit() # Make a deposit
38 account1.withdraw() # Make a withdrawal
39 print("Balance after deducting fees:", account1.bankfees()) # Calculate and display balance after fees
6
Explanation:
• Line 1: Define a class named BankAccount to represent a bank account.
• Line 2: Define the __init__ method that takes account ID, name, and balance as parameters.
• Lines 3-5: Initialize the object's attributes with the provided values.
• Line 6: Print a welcome message when a new account is created.
• Line 8: Define a deposit method that allows the user to add money to the account.
• Line 9: Get the amount to deposit from the user and convert it to a float.
• Line 10: Add the deposit amount to the account balance.
• Line 11: A commented alternative way to perform the addition.
• Lines 12-13: Print confirmation messages and the new balance.
• Line 15: Define a withdraw method that allows the user to withdraw money from the account.
• Line 16: Get the amount to withdraw from the user and convert it to a float.
• Lines 17-18: Check if the withdrawal amount exceeds the balance, and if so, print an error message.
• Lines 19-22: If there are sufficient funds, subtract the withdrawal amount from the balance and print confirmation messages.
• Line 24: Define a display method that shows the account information.
• Lines 25-27: Print the account ID, name, and balance.
• Line 29: Define a bankfees method that calculates the balance after deducting 5% bank fees.
• Line 30: Return 95% of the account balance (which represents deducting 5% fees).
• Line 33: Create a BankAccount object with specific ID, name, and balance values.
• Lines 36-39: Call the various methods on the account object to test its functionality.
Additional Notes on Object-Oriented Programming
Key OOP Concepts Demonstrated in These Solutions:
1. Classes and Objects: Each solution defines a class that serves as a blueprint for objects, and then creates instances (objects) of that
class.
2. Encapsulation: The class attributes (like width, height, x, y, balance) are encapsulated within the class, and accessed/modified through
7
methods.
3. Methods: Each class defines methods that operate on the object's data, such as calculating area, adding vectors, or performing banking
operations.
4. Constructor: The __init__ method is a special method that initializes new objects with specific attributes.
5. Instance Variables: Variables that are unique to each instance of a class, prefixed with self.