class and object

Python class and object problems - Solution

February 04, 20246 min read

Problem 1: Creating a Book Class

Problem Statement:

Design a Book class in Python that has the following attributes and methods:

Attributes:

  • title (string): the title of the book.

  • author (string): the author of the book.

  • price (float): the price of the book.

  • quantity (int): the quantity of the book in stock.

Methods:

  • __init__(self, title, author, price, quantity): Initializes a new book object with the given title, author, price, and quantity.

  • get_price(self): Returns the price of the book.

  • set_price(self, new_price): Sets a new price for the book.

  • get_quantity(self): Returns the quantity of the book in stock.

  • set_quantity(self, new_quantity): Sets a new quantity for the book in stock.

  • sell(self, number_sold): Decreases the quantity of books in stock by number_sold. If number_sold is more than the available quantity, print "Not enough stock".

  • restock(self, number_added): Increases the quantity of books in stock by number_added.

Example Usage:

# Create a new book instance
my_book = Book(title="1984", author="George Orwell", price=29.99, quantity=100)

# Get and set price
print(my_book.get_price())  # Output: 29.99
my_book.set_price(24.99)

# Sell and restock
my_book.sell(5)
print(my_book.get_quantity())  # Output: 95
my_book.restock(10)
print(my_book.get_quantity())  # Output: 105

Solution:

class Book:
    def __init__(self, title, author, price, quantity):
        self.title = title
        self.author = author
        self.price = price
        self.quantity = quantity
        
    def get_price(self):
        return self.price
    
    def set_price(self, new_price):
        self.price = new_price
        
    def get_quantity(self):
        return self.quantity
    
    def set_quantity(self, new_quantity):
        self.quantity = new_quantity
        
    def sell(self, number_sold):
        if number_sold > self.quantity:
            print("Not enough stock")
        else:
            self.quantity -= number_sold
            
    def restock(self, number_added):
        self.quantity += number_added
        
# Test the class
my_book = Book(title="1984", author="George Orwell", price=29.99, quantity=100)
print(my_book.get_price())  # Output: 29.99
my_book.set_price(24.99)
my_book.sell(5)
print(my_book.get_quantity())  # Output: 95
my_book.restock(10)
print(my_book.get_quantity())  # Output: 105

Problem 2: Implementing a Circle Class

Problem Statement:

Create a Circle class in Python that represents a circle with the following specifications:

Attributes:

  • radius (float): The radius of the circle.

Methods:

  • __init__(self, radius): Initializes a new circle object with the given radius.

  • area(self): Returns the area of the circle.

  • circumference(self): Returns the circumference of the circle.

Constants:

  • PI (float): A class-level constant representing the value of π (pi).

Example Usage:

# Create a new circle instance
my_circle = Circle(radius=5)

# Get area and circumference
print(my_circle.area())  # Output: 78.54 (approximately)
print(my_circle.circumference())  # Output: 31.42 (approximately)

Solution:

class Circle:
    PI = 3.141592653589793
    
    def __init__(self, radius):
        self.radius = radius
        
    def area(self):
        return Circle.PI * self.radius ** 2
    
    def circumference(self):
        return 2 * Circle.PI * self.radius
        
# Test the class
my_circle = Circle(radius=5)
print(my_circle.area())  # Output: 78.54 (approximately)
print(my_circle.circumference())  # Output: 31.42 (approximately)

Problem 3: Building a Bank Account Class

Problem Statement:

Design a BankAccount class in Python with the following attributes and methods:

Attributes:

  • account_number (string): The account number.

  • balance (float): The balance in the account.

Methods:

  • __init__(self, account_number, initial_balance): Initializes a new bank account object with the given account number and an initial balance.

  • deposit(self, amount): Deposits the given amount into the account. If the amount is negative, print "Invalid amount".

  • withdraw(self, amount): Withdraws the given amount from the account. If the amount is greater than the balance, print "Insufficient funds".

  • get_balance(self): Returns the current balance of the account.

Example Usage:

# Create a new bank account instance
my_account = BankAccount(account_number="12345678", initial_balance=1000)

# Deposit and withdraw
my_account.deposit(500)
my_account.withdraw(200)
print(my_account.get_balance())  # Output: 1300

Solution:

class BankAccount:
    def __init__(self, account_number, initial_balance):
        self.account_number = account_number
        self.balance = initial_balance
        
    def deposit(self, amount):
        if amount < 0:
            print("Invalid amount")
        else:
            self.balance += amount
            
    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds")
        else:
            self.balance -= amount
            
    def get_balance(self):
        return self.balance
        
# Test the class
my_account = BankAccount(account_number="12345678", initial_balance=1000)
my_account.deposit(500)
my_account.withdraw(200)
print(my_account.get_balance())  # Output: 1300

Problem 4: Creating a Vehicle Class

Problem Statement:

Develop a Vehicle class in Python with the following details:

Attributes:

  • make (string): The make of the vehicle (e.g., Toyota, Ford).

  • model (string): The model of the vehicle (e.g., Camry, Mustang).

  • year (int): The year the vehicle was manufactured.

  • mileage (int): The current mileage of the vehicle.

Methods:

  • __init__(self, make, model, year, mileage): Initializes a new vehicle object with the specified make, model, year, and mileage.

  • drive(self, miles): Increments the mileage of the vehicle by the specified number of miles.

  • get_info(self): Returns a string containing the make, model, year, and mileage of the vehicle.

Example Usage:

# Create a new vehicle instance
my_vehicle = Vehicle(make="Toyota", model="Camry", year=2020, mileage=25000)

# Drive the vehicle
my_vehicle.drive(200)

# Get vehicle info
print(my_vehicle.get_info())  # Output: "Toyota Camry, 2020, 25200 miles"

Solution:

class Vehicle:
    def __init__(self, make, model, year, mileage):
        self.make = make
        self.model = model
        self.year = year
        self.mileage = mileage
        
    def drive(self, miles):
        self.mileage += miles
            
    def get_info(self):
        return f"{self.make} {self.model}, {self.year}, {self.mileage} miles"
        
# Test the class
my_vehicle = Vehicle(make="Toyota", model="Camry", year=2020, mileage=25000)
my_vehicle.drive(200)
print(my_vehicle.get_info())  # Output: "Toyota Camry, 2020, 25200 miles"

Problem 5: Implementing a Student Class

Problem Statement:

Create a Student class in Python with the following attributes and methods:

Attributes:

  • name (string): The name of the student.

  • grades (list of floats): The list of grades for the student.

Methods:

  • __init__(self, name): Initializes a new student object with the given name and an empty grade list.

  • add_grade(self, grade): Adds a new grade to the student's grade list.

  • get_average(self): Returns the average of the student's grades.

Example Usage:

# Create a new student instance
student = Student(name="Alice")

# Add grades and get average
student.add_grade(90)
student.add_grade(95)
student.add_grade(85)
print(student.get_average())  # Output: 90.0

Solution:

class Student:
    def __init__(self, name):
        self.name = name
        self.grades = []
        
    def add_grade(self, grade):
        self.grades.append(grade)
            
    def get_average(self):
        return sum(self.grades) / len(self.grades)
        
# Test the class
student = Student(name="Alice")
student.add_grade(90)
student.add_grade(95)
student.add_grade(85)
print(student.get_average())  # Output: 90.0

Problem 6: Building a Rectangle Class

Problem Statement:

Design a Rectangle class in Python to represent a rectangle with the following characteristics:

Attributes:

  • length (float): The length of the rectangle.

  • width (float): The width of the rectangle.

Methods:

  • __init__(self, length, width): Initializes a new rectangle object with the specified length and width.

  • area(self): Returns the area of the rectangle.

  • perimeter(self): Returns the perimeter of the rectangle.

Example Usage:

# Create a new rectangle instance
rectangle = Rectangle(length=5, width=3)

# Calculate area and perimeter
print(rectangle.area())      # Output: 15
print(rectangle.perimeter()) # Output: 16

Solution:

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
        
    def area(self):
        return self.length * self.width
    
    def perimeter(self):
        return 2 * (self.length + self.width)
        
# Test the class
rectangle = Rectangle(length=5, width=3)
print(rectangle.area())      # Output: 15
print(rectangle.perimeter()) # Output: 16

Problem 7: Creating a Temperature Converter Class

Problem Statement:

Implement a Temperature class in Python that can convert temperatures between Fahrenheit and Celsius with the following specifics:

Attributes:

  • temperature (float): The temperature value.

  • unit (string): The unit of the temperature ('C' for Celsius, 'F' for Fahrenheit).

Methods:

  • __init__(self, temperature, unit): Initializes a new temperature object with the specified temperature and unit.

  • convert_to_fahrenheit(self): Converts the temperature to Fahrenheit and updates the unit.

  • convert_to_celsius(self): Converts the temperature to Celsius and updates the unit.

Example Usage:

# Create a new temperature instance in Celsius
temp = Temperature(temperature=0, unit='C')

# Convert to Fahrenheit
temp.convert_to_fahrenheit()
print(temp.temperature)  # Output: 32.0

# Convert back to Celsius
temp.convert_to_celsius()
print(temp.temperature)  # Output: 0.0

Solution:

class Temperature:
    def __init__(self, temperature, unit):
        self.temperature = temperature
        self.unit = unit
        
    def convert_to_fahrenheit(self):
        if self.unit == 'C':
            self.temperature = self.temperature * 9/5 + 32
            self.unit = 'F'
            
    def convert_to_celsius(self):
        if self.unit == 'F':
            self.temperature = (self.temperature - 32) * 5/9
            self.unit = 'C'
        
# Test the class
temp = Temperature(temperature=0, unit='C')
temp.convert_to_fahrenheit()
print(temp.temperature)  # Output: 32.0
temp.convert_to_celsius()
print(temp.temperature)  # Output: 0.0

blog author image

sunil s

Quant Developer & Mentor

Back to Blog