1.
Create a Python program to define a class `MyClass` with attributes `name` and `age`, instantiate the class, and use the instance to access these
attributes. (Difficulty: Easy)
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
# Instantiate the class
my_object = MyClass("Alice", 25)
# Access attributes
print(f"Name: {my_object.name}, Age: {my_object.age}")
2. Write a Python program to define a class `Car` with a default constructor that initializes attributes for `brand` and `year`. Include a method
`display_info` to print the car's details. Create an object of the class and call the method to display the information. (Difficulty: Easy)
class Car:
def __init__(self):
self.brand = "Toyota"
self.year = 2020
def display_info(self):
print(f"Brand: {self.brand}, Year: {self.year}")
# Create an object and call the method
my_car = Car()
my_car.display_info()
3. Develop a Python program that defines a class `Animal` with a constructor accepting `name` and `age` as parameters, along with a method
`display_info` to print these details. Create an instance of the class and call the method to display the animal's information. (Difficulty: Easy)
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Create an instance and call the method
my_animal = Animal("Dog", 5)
my_animal.display_info()
4. Write a Python program to demonstrate the functionality of the `Bank` class by creating an instance with attributes `name`, `accno`, and `phno`.
Showcase how to access its public, private, and protected attributes. (Difficulty: Easy)
class Bank:
def __init__(self, name, accno, phno):
self.name = name # Public attribute
self._accno = accno # Protected attribute
self.__phno = phno # Private attribute
def get_private_phno(self):
return self.__phno
@property
def private_phno(self):
return self.__phno
@private_phno.setter
def private_phno(self, value):
if len(str(value))==10 and str(value).isdigit(): # Example condition to control setting
self.__phno = value
else:
raise ValueError("Phno to contain 10 digit")
# Instantiate the class
bank_account = Bank("John Doe", "123456", "9876543210")
# Access attributes
print(f"Name: {bank_account.name}") # Public
print(f"Account Number: {bank_account._accno}") # Protected
#Method 1 - Access the private attribute using the instance method
print(f"Phone Number(using instance method): {bank_account.get_private_phno()}") # Private (via method)
#Method 2 - Access the private attribute using the mangled name
print(f"Phone Number(Using mangled name): {bank_account._Bank__phno}") # Private (via name mangling)
#Method 3 - Access the private attribute using the decorator @property and @attributename.setter
# Access private attribute via property (getter)
print(f"Phone Number(Using decorator property): {bank_account.private_phno}")
# Set private attribute via property (setter)
bank_account.private_phno = "9000290001"
print(f"Updated Phone Number(Using decorator property setter): {bank_account.private_phno}")
5. Create a Python program to define a class `Student` with private attributes `name` and `regno`. Instantiate an object of the class, access its
private attributes, and update the `name` attribute. (Difficulty: Medium)
class Student:
def __init__(self, name, regno):
self.__name = name # Private attribute
self.__regno = regno
def get_name(self):
return self.__name
def set_name(self, new_name):
self.__name = new_name
# Create an instance
student = Student("Amir", "12345")
#Method1 - Using get and set instance methods
# Access and update private attribute
print(f"Original Name: {student.get_name()}")
student.set_name("Ali")
print(f"Updated Name: {student.get_name()}")
#Method2 - Using Name mangling
print(f"Original Name: {student._Student_name}")
student._Student__name = "Ali"
print(f"Updated Name: {student._Student_name}")
6. Write a Python program to define a class `Car` with attributes `make`, `model`, `mileage`, and `price`. Include methods to display the car's details,
start and stop the car, and update its price. Create two car objects and demonstrate the functionality by calling their methods. (Difficulty: Easy)
class Car:
def __init__(self, make, model, mileage, price):
self.make = make
self.model = model
self.mileage = mileage
self.price = price
def display_details(self):
print(f"Make: {self.make}, Model: {self.model}, Mileage: {self.mileage}, Price: {self.price}")
def start(self):
print(f"The {self.make} {self.model} is starting.")
def stop(self):
print(f"The {self.make} {self.model} is stopping.")
def update_price(self, new_price):
self.price = new_price
print(f"The price of the car has been updated to {self.price}.")
# Create car objects
car1 = Car("Toyota", "Corolla", 30000, 20000)
car2 = Car("Honda", "Civic", 25000, 22000)
# Demonstrate functionality
car1.display_details()
car1.start()
car1.update_price(18000)
car1.stop()
car2.display_details()
7. Create a Python program to define a class `Movie` with attributes `Heroname` and `year`. Instantiate the class and use the instance to access
these attributes. (Difficulty: Easy)
class Movie:
def __init__(self, heroname, year):
self.heroname = heroname
self.year = year
# Instantiate and access attributes
movie = Movie("John Wick", 2014)
print(f"Hero Name: {movie.heroname}, Year: {movie.year}")
8. Write a Python program to create a class `Student` with a protected attribute `_name` initialized to `"Amir"` in the constructor. Create an object of
the class and print the protected attribute. (Difficulty: Easy)
class Student:
def __init__(self):
self._name = "Amir" # Protected attribute
# Create an object and print the protected attribute
student = Student()
print(f"Protected Name: {student._name}")
9. Develop a Python program to define a class `College` with a private attribute `__name`, initialized through the constructor. Instantiate an object of
the class with the name `"Presidency"` and access the private attribute using an instance method. (Difficulty: Easy)
class College:
def __init__(self, name):
self.__name = name # Private attribute
def get_name(self):
return self.__name
# Instantiate and access private attribute using method
college1 = College("Presidency")
#Method 1 - Access the private attribute using the instance method
print(f"College Name: {college1.get_name()}")
#Method 2 - Access the private attribute using the mangled name
print(f"College Name(Using mangled name): {college1._College__name}") # Private (via name mangling)
10. Write a Python program to create a class `Sms` with three attributes (`source1`, `source2`, and `source3`) representing different social media
sources. These should be public, protected, and private, respectively. Initialize them to `"Whatsapp"`, `"Instagram"`, and `"Facebook"`. Create an
instance of the class and print the values of each attribute. (Difficulty: Medium)
class Sms:
def __init__(self):
self.source1 = "Whatsapp" # Public attribute
self._source2 = "Instagram" # Protected attribute
self.__source3 = "Facebook" # Private attribute
def get_private_source(self):
return self.__source3
# Create an instance and print attribute values
sms1 = Sms()
print(f"Public Source: {sms1.source1}")
print(f"Protected Source: {sms1._source2}")
#Method 1 - Access the private attribute using the instance method
print(f"Private Source: {sms1.get_private_source()}")
#Method 2 - Access the private attribute using the mangled name
print(f"Phone Number(Using mangled name): {sms1._Sms__source3}") # Private (via name mangling)
11. Create a Python program defining a class `Person` with private attributes `__name` and `__age`. Implement getter and setter methods for both,
with validation to ensure `age` is positive. Instantiate the class with `name = "John"` and `age = 25`, print the values using getters, update `age` to
30 using the setter, and print the updated age. (Difficulty: Easy)
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def set_name(self, name):
self.__name = name
def set_age(self, age):
if age > 0:
self.__age = age
else:
print("Age must be positive.")
# Instantiate the class and use getters and setters
person1 = Person("John", 25)
print(f"Name: {person1.get_name()}, Age: {person1.get_age()}")
# Update age
person1.set_age(30)
print(f"Updated Age: {person1.get_age()}")
person2 = Person("Wick", 55)
#Method 2 - Access the private attribute using the mangled name
print(f"Name: {person2.get_name()}, Age: {person2._Person__age}")
# Update age
person2._Person__age=60
print(f"Updated Age(Using mangled name): {person2._Person__age}") # Private (via name mangling)
12. Demonstrate the functionality of the `Bank` class by creating an instance with attributes `name`, `accno`, and `phno`. Show how to access
public, protected, and private attributes, including a method to retrieve the private attribute. (Difficulty: Easy)
class Bank:
def __init__(self, name, accno, phno):
self.name = name # Public attribute
self._accno = accno # Protected attribute
self.__phno = phno # Private attribute
def get_private_phno(self):
return self.__phno
@property
def private_phno(self):
return self.__phno
# Instantiate and access attributes
bank1 = Bank("John Doe", "123456", "9876543210")
print(f"Name: {bank1.name}") # Public
print(f"Account Number: {bank1._accno}") # Protected
#Method 1 - Access the private attribute using the instance method
print(f"Phone Number: {bank1.get_private_phno()}") # Private (via method)
#Method 2 - Access the private attribute using the mangled name
print(f"Phone Number(Using mangled name): {bank1._Bank__phno}") # Private (via name mangling)
#Method 3 - Access the private attribute using the decorator @property and @attributename.setter
# Access private attribute via property (getter)
print(f"Phone Number(Using decorator property): {bank1.private_phno}")
13.Write a Python program to define an `Employee` class with the following:
● 1. A non-parameterized constructor that initializes attributes (`employee_id`, `name`, `department`, and `salary`) to `None` or default values.
● 2. A public method `set_employee_details()` to set the attribute values using the provided parameters.
● 3. A public method `display_employee_details()` to display the employee's details.
Create two objects of the `Employee` class. Use `display_employee_details()` to check the initial attribute values. Then, use
`set_employee_details()` to update the attribute values and call `display_employee_details()` again to verify the updated values. (Difficulty: Easy)
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def set_name(self, name):
self.__name = name
def set_age(self, age):
if age > 0:
self.__age = age
else:
print("Age must be positive.")
# Instantiate the class and use getters and setters
person1 = Person("John", 25)
print(f"Name: {person1.get_name()}, Age: {person1.get_age()}")
# Update age
person1.set_age(30)
print(f"Updated Age: {person1.get_age()}")
person2 = Person("Wick", 55)
#Method 2 - Access the private attribute using the mangled name
print(f"Name: {person2.get_name()}, Age: {person2._Person__age}")
# Update age
person2._Person__age=60
print(f"Updated Age(Using mangled name): {person2._Person__age}") # Private (via name mangling)
14. Develop a Python program to define a `Student` class with the following:
● 1. A non-parameterized constructor that initializes attributes (`student_id`, `name`, and `grade`) to `None` or default values.
● 2. A public method `set_student_details()` to set the attribute values using the provided parameters.
● 3. A public method `display_student_details()` to display the student's details.
Create two objects of the `Student` class. Call `display_student_details()` to check the initial values. Use `set_student_details()` to update the
attributes, then call `display_student_details()` again to verify the updates. (Difficulty: Easy)
class Student:
def __init__(self):
self.student_id = None
self.name = None
self.grade = None
def set_student_details(self, student_id, name, grade):
self.student_id = student_id
self.name = name
self.grade = grade
def display_student_details(self):
print(f"ID: {self.student_id}, Name: {self.name}, Grade: {self.grade}")
# Create objects and demonstrate functionality
student1 = Student()
student2 = Student()
# Initial values
student1.display_student_details()
student2.display_student_details()
# Set and display updated details
student1.set_student_details(1, "Charlie", "A")
student2.set_student_details(2, "Diana", "B")
student1.display_student_details()
student2.display_student_details()
15. Create a Python program that defines a `Person` class with:
● 1. A non-parameterized constructor to initialize attributes (`name`, `age`, `address`, and `phone_number`) to `None` or default values.
● 2. A public method `set_person_details()` to set the attribute values using provided parameters.
● 3. A public method `display_person_details()` to display the person's details.
Instantiate two objects of the `Person` class. Use `display_person_details()` to check the initial values, then use `set_person_details()` to update the
attributes and verify the updates using `display_person_details()`. (Difficulty: Easy)
class Person:
def __init__(self):
self.name = None
self.age = None
self.address = None
self.phone_number = None
def set_person_details(self, name, age, address, phone_number):
self.name = name
self.age = age
self.address = address
self.phone_number = phone_number
def display_person_details(self):
print(f"Name: {self.name}, Age: {self.age}, Address: {self.address}, Phone: {self.phone_number}")
# Create objects and demonstrate functionality
person1 = Person()
person2 = Person()
# Initial values
person1.display_person_details()
person2.display_person_details()
# Set and display updated details
person1.set_person_details("Eve", 30, "123 Main St", "123-456-7890")
person2.set_person_details("Frank", 40, "456 Elm St", "987-654-3210")
person1.display_person_details()
person2.display_person_details()
16. Write a Python program to define a `Book` class with the following:
● 1. Attributes: `title` (public), `author` (protected), and `publisher` (private).
● 2. Use a parameterized constructor to initialize these attributes.
● 3. Access and display each attribute, demonstrating how public, protected, and private attributes can be accessed.(Difficulty: Hard)
class Book:
def __init__(self, title, author, publisher):
self.title = title # Public attribute
self._author = author # Protected attribute
self.__publisher = publisher # Private attribute
def get_publisher(self):
return self.__publisher
@property
def private_publisher(self):
return self.__publisher
@private_publisher.setter
def private_publisher(self, value):
if len(str(value))>0 or str(value).isalpha(): # Example condition to control setting
self.__publisher = value
else:
raise ValueError("Publisher to contain only alphabets no special characters and numbers allowed")
# Instantiate and access attributes
book1 = Book("1984", "George Orwell", "Secker & Warburg")
print(f"Title: {book1.title}") # Public
print(f"Author: {book1._author}") # Protected
#Method 1 - Access the private attribute using the instance method
print(f"Publisher: {book1.get_publisher()}") # Private (via method)
#Method 2 - Access the private attribute using the mangled name
print(f"Publisher(Using mangled name): {book1._Book__publisher}") # Private (via name mangling)
#Method 3 - Access the private attribute using the decorator @property and @attributename.setter
# Access private attribute via property (getter)
print(f"Publisher(Using decorator property): {book1.private_publisher}")
# Set private attribute via property (setter)
book1.private_publisher = "Penguin"
print(f"Updated Publisher(Using decorator property setter): {book1.private_publisher}")
17. Create a Python program to define an `Employee` class with the following:
● 1. Attributes: `employee_id`, `name`, `department`, and `salary`.
● 2. A method `calculate_salary()` that calculates the total salary based on:
○ - Required input: basic salary.
○ - Optional inputs: bonus and overtime hours.
○ - Overtime pay is calculated at a rate of INR 750 per hour.
○ - If only the basic salary is provided, the total salary equals the basic salary. If bonus and/or overtime are provided, include them in
the total salary.(Difficulty: Medium)
class Employee:
def __init__(self, employee_id, name, department, salary):
self.employee_id = employee_id
self.name = name
self.department = department
self.salary = salary
def calculate_salary(self, basic_salary, bonus=0, overtime_hours=0):
overtime_pay = overtime_hours * 750
total_salary = basic_salary + bonus + overtime_pay
return total_salary
# Create an employee object and calculate salaries
employee = Employee(101, "Alice", "IT", 50000)
print(f"Total Salary (Basic only): {employee.calculate_salary(50000)}")
print(f"Total Salary (With Bonus and Overtime): {employee.calculate_salary(50000, 10000, 5)}")
18. Write a Python program to define a `Book` class with the following:
● 1. A non-parameterized constructor that initializes attributes to `None`.
● 2. A public method `set_book_details()` to set attribute values using the provided parameters.
● 3. A public method `display_book_details()` to display the book's details.
Create two objects of the `Book` class. Call `display_book_details()` to check the initial values, then use `set_book_details()` to update the attributes
and call `display_book_details()` again to verify the updates. (Difficulty: Easy)
class Book:
def __init__(self):
self.title = None
self.author = None
self.publisher = None
def set_book_details(self, title, author, publisher):
self.title = title
self.author = author
self.publisher = publisher
def display_book_details(self):
print(f"Title: {self.title}, Author: {self.author}, Publisher: {self.publisher}")
# Create two book objects
book1 = Book()
book2 = Book()
# Initial values
book1.display_book_details()
book2.display_book_details()
# Update and display details
book1.set_book_details("1984", "George Orwell", "Secker & Warburg")
book2.set_book_details("To Kill a Mockingbird", "Harper Lee", "J.B. Lippincott & Co.")
book1.display_book_details()
book2.display_book_details()
19. Write a Python program to define a `Book` class with:
● 1. An constructor method to initialize the `title`, `author`, and `price` attributes.
● 2. An instance method `display_book_details()` to display the book's attributes.
● 3. A class variable `no_of_books` to track the number of book objects created.
● 4. A class method `get_no_of_books_created()` to return the count of book objects created.
Create multiple book objects and demonstrate the functionality of class and instance methods. (Difficulty: Medium)
class Book:
no_of_books = 0 # Class variable
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
Book.no_of_books += 1
def display_book_details(self):
print(f"Title: {self.title}, Author: {self.author}, Price: {self.price}")
@classmethod
def get_no_of_books_created(cls):
return cls.no_of_books
# Create book objects and demonstrate functionality
book1 = Book("1984", "George Orwell", 500)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 600)
book1.display_book_details()
book2.display_book_details()
print(f"Number of books created: {Book.get_no_of_books_created()}")
20. Develop a Python program to define a `Book` class with:
● 1. An constructor method to initialize the `title`, `author`, and `price` attributes.
● 2. An instance method `display_book_details()` to display the book's attributes.
● 3. A static method `validate_price()` to ensure the price is valid (non-negative and greater than zero).
● 4. An instance method `check_if_discount_available()` to return `True` if a discount is available (price > 999), otherwise `False`.
Create multiple book objects and demonstrate the functionality of instance, static, and class methods. (Difficulty: Hard)
class Book:
no_of_books = 0 # Class variable
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
Book.no_of_books += 1
def display_book_details(self):
print(f"Title: {self.title}, Author: {self.author}, Price: {self.price}")
@staticmethod
def validate_price(price):
return price > 0
def check_if_discount_available(self):
return self.price > 999
@classmethod
def get_no_of_books_created(cls):
return cls.no_of_books
# Create book objects and demonstrate functionality
book1 = Book("1984", "George Orwell", 1200)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 800)
book1.display_book_details()
book2.display_book_details()
# Validate prices
print(f"Is the price of book1 valid? {Book.validate_price(book1.price)}")
print(f"Is the price of book2 valid? {Book.validate_price(book2.price)}")
# Check for discounts
print(f"Does book1 have a discount? {book1.check_if_discount_available()}")
print(f"Does book2 have a discount? {book2.check_if_discount_available()}")
# Get the number of books created
print(f"Number of books created: {Book.get_no_of_books_created()}")