Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

PythonLab_4

The document outlines a programming lab focused on creating and modifying a Car class in Python, including features like encapsulation, inheritance, and magic methods. It also covers basic functions, default parameters, lambda functions, recursion, and dictionary iteration. Examples are provided for each concept, demonstrating how to implement them in code.

Uploaded by

Muhammad Haider
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PythonLab_4

The document outlines a programming lab focused on creating and modifying a Car class in Python, including features like encapsulation, inheritance, and magic methods. It also covers basic functions, default parameters, lambda functions, recursion, and dictionary iteration. Examples are provided for each concept, demonstrating how to implement them in code.

Uploaded by

Muhammad Haider
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

lj3ceaaqp

March 28, 2025

1 Lab 4
1.1 Muhammad Haider
1.2 ITF-11126
##1. Create a Simple Class: ### Define a class Car with attributes brand, model, and year.
### Create an instance of the class and print the attributes.
[1]: class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year

my_car = Car("Toyota", "Corolla", 2022)

print(f"Brand: {my_car.brand}")
print(f"Model: {my_car.model}")
print(f"Year: {my_car.year}")

Brand: Toyota
Model: Corolla
Year: 2022

1.3 2. Class with a Method:


1.3.1 Extend the Car class by adding a method display_info() that prints the details
of the car.
[3]: class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year

def display_info(self):
print(f"Car Info: {self.year} {self.brand} {self.model}")

1
my_car = Car("Toyota", "Corolla", 2022)

my_car.display_info()

Car Info: 2022 Toyota Corolla

1.4 3. Encapsulation with Getters and Setters:


Modify the Car class to make the year attribute private (_year). Add getter and setter methods to
access and update year. ## 4. Inheritance in Python Classes: Create a subclass ElectricCar that
inherits from Car. Add a new attribute battery_capacity and a method battery_info() to display
the battery capacity.
[5]: class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self._year = year

def get_year(self):
return self._year

def set_year(self, year):


if year > 1885:
self._year = year
else:
print("Invalid year!")

def display_info(self):
print(f"Car Info: {self._year} {self.brand} {self.model}")

class ElectricCar(Car):
def __init__(self, brand, model, year, battery_capacity):
super().__init__(brand, model, year)
self.battery_capacity = battery_capacity

def battery_info(self):
print(f"Battery Capacity: {self.battery_capacity} kWh")

2
my_car = Car("Toyota", "Corolla", 2022)
my_car.display_info()

print(my_car.get_year())
my_car.set_year(2025)
print(my_car.get_year())

my_electric_car = ElectricCar("Tesla", "Model S", 2023, 100)


my_electric_car.display_info()
my_electric_car.battery_info()

Car Info: 2022 Toyota Corolla


2022
2025
Car Info: 2023 Tesla Model S
Battery Capacity: 100 kWh

1.5 5. Magic Methods (str and repr):


Modify the Car class to override the str method to return a formatted string when printing an
object.
[6]: class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self._year = year

def get_year(self):
return self._year

def set_year(self, year):


if year > 1885:
self._year = year
else:
print("Invalid year!")

def display_info(self):
print(f"Car Info: {self._year} {self.brand} {self.model}")

def __str__(self):
return f"{self._year} {self.brand} {self.model}"

my_car = Car("Toyota", "Corolla", 2022)


print(my_car)

3
2022 Toyota Corolla
##Basic Function: Write a function calculate_sum(a, b) that takes two numbers and returns their
sum.
##7. Function with Default Parameters: Create a function greet(name=“Guest”) that prints
“Hello, {name}!”. If no name is provided, it should greet “Guest” by default. ##8. Lambda
Function: Write a lambda function to find the square of a number and apply it to a list [2, 4, 6, 8]
using the map() function.
##9. Recursive Function: Implement a recursive function to calculate the factorial of a number.
[7]: def calculate_sum(a, b):
return a + b

def greet(name="Guest"):
print(f"Hello, {name}!")

square = lambda x: x ** 2
numbers = [2, 4, 6, 8]
squared_numbers = list(map(square, numbers))

def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)

print(calculate_sum(5, 10))
greet()
greet("Alice")
print(squared_numbers)
print(factorial(5))

15
Hello, Guest!
Hello, Alice!
[4, 16, 36, 64]
120

1.6 10. Looping through a Dictionary:


Create a dictionary student_scores = {‘Alice’: 85, ‘Bob’: 78, ‘Charlie’: 92} Use a for loop to iterate
through the dictionary and print each student’s name along with their score.
[8]: student_scores = {'Alice': 85, 'Bob': 78, 'Charlie': 92}

for name, score in student_scores.items():


print(f"{name}: {score}")

Alice: 85
Bob: 78
Charlie: 92

You might also like