0% found this document useful (0 votes)
8 views

Sample Question Bank-Solved.ipynb - Colab

Uploaded by

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

Sample Question Bank-Solved.ipynb - Colab

Uploaded by

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

keyboard_arrow_down Classes & Objects

keyboard_arrow_down Data Encapsulation & Data Hiding using access specifiers (Private, Protected and Public)
class Employee:
company="Tech Corp" #class variable
def __init__(self):
self.__emp_id=1001 #instance variable - private
self.__name="Afeef" #instance variable - private
self.salary=20000 #instance variable -public
def get __emp_id(self):
return __emp_id
def display_employee(self):
print(self.__emp_id)
print(self.__name)
print(self.company)
emp1=Employee()
print(get __emp_id()) # accessing private variable
emp1.display_employee() # accessing public method

class Parrot:
def __init__(self,name,age):
self.name=name #instance variable
self.age=age #instance variable
name= ['kingfisher','woodpecker'] #local variable
age=[18,20] #local variable
print("parrot name is ",self.name)
print("parrot name is",name[0],name[1])
def show_info(self)->list:
return [self.name,self.age]
parrot1=Parrot('preeti',18) #creating an instance of the class
parrot2=Parrot('priya',20) #creating 2nd object
print(parrot1.show_info()[0],"is",parrot1.show_info()[1],"years old")
print(parrot2.show_info()[0],"is",parrot2.show_info()[1],"years old")

class Employee:
def __init__(self, employee_id, name, department, salary, basic_salary, bonus=0, overtime_hours=0):
self.employee_id = employee_id
self.name = name
self.department = department
self.salary = salary
self.basic_salary = basic_salary
self.bonus = bonus
self.overtime_hours = overtime_hours

def calculate_salary(self):

self.salary = self.basic_salary + self.bonus + self.overtime_hours * 750


return self.salary

e=Employee(122,"Kiran","k",2000,2000,1,2)
e.calculate_salary()

class Book:
def __init__(self):
self.name = "harry potter"
self.author = "yeshas"
self.year = "2003"

def book_details(self):
return{"Book name":self.name,
"Book author":self.author,
"Book published":self.year}
b = Book()
print(b.book_details())
help(b.book_details)

class Employee:
def __init__(self,employee_id,name,department,basic_salary,bonus=0,overtime_hours=0):
self.employee_id=employee_id
self.name=name
self.department=department
self.basic_salary=basic_salary
self.bonus=bonus
self.overtime_hours=overtime_hours
def calculate_salary(self):
total_salary=self.basic_salary
if self.bonus>0:
total_salary+=self.bonus
if self.overtime_hours>0:
overtime_pay=self.overtime_hours*750
total_salary+=overtime_pay
return total_salary
emp1=Employee(employee_id=101,name="Mateen",department="cse",basic_salary=50000,bonus=500,overtime_hours=10)
print(f"The salary of {emp1.name} is:{emp1.calculate_salary()} INR")

keyboard_arrow_down Question 1:

Create a class Book with the following property as title,year,author_name:

A public method display_book_details() that displays the book details.

class Book:
def __init__(self,title,year,author_name):
self.title=title
self.year=year
self.author_name=author_name

def display_info_(Book):
print(f"Title:{self.title},Year:{self.year},Author_name:{self.author_name}")
return(Book)

book1=Book("devil",2004,"john versonda")

class Book:
def __init__(self,name,author,year):
self.name=name
self.author=author
self.year=year

def display():

print(f"Name of the book:"(self.name))


print(f"author:"(self.author))
print(f"year:"(self.year))

ob=Book(self,"x","yy",2021)
ob.disp

keyboard_arrow_down Question 1:

Create a class College with the following property as name:

A public method that displays the name.

class college:
def __init__(self,name):
self.__name=name
def get_name(self):
return self.__name
college=college("presidency")
print("college name:", college.get_name())

keyboard_arrow_down Question 1

Demonstrate a Python program to define a class Parrot with attributes name and age, create two objects of the class (parrot1 and parrot2),
assign values to their attributes, and access the attributes

class Parrot:
name="" #class variable
age=0 #class variable

parrot1=Parrot()
parrot1.name="Rio"
parrot1.age=20
parrot2=Parrot()
parrot2.name="venice"
parrot2.age=12
print(f"I am {parrot1.name} and my age is {parrot1.age}")
print(f"I am {parrot2.name} and my age is {parrot2.age}")
I am Rio and my age is 20
I am venice and my age is 12

keyboard_arrow_down Question 1:

Create a class User with the following property as name,username,bio:

A public method display_profile() that displays the user details.

class user:
def __init__(self,name,username,bio):
self.name=name
self.username=username
self.bio=bio
def display_profile(self):
print(f"name is :{self.name}")
print(f"username is :{self.username}")
print(f"bio is :{self.bio}")
obj=user("bhagesh","pintu@lingu","iamkabaddi player")
print(obj.display_profile())
print(obj.name)
print(obj.username)
print(obj.bio)

class user():
def __init__(self):
self.name="lohitha"
self.username="lohithai"
self.bio="hospet"
def display_profile(self):
print(f"{self.name} {self.username} {self.bio}")
obj=user()
obj.display_profile()

keyboard_arrow_down Question 1:

Create a class Bank with the following property as name which is public attribute and accno which is private:

A getter method () that displays the bank private attribute details.

# Bank class
class Bank:
def __init__(self, name , accno, phno):
self.name = name
self._accno = accno
self.__phno = phno

def get_private_phno(self):
return self.__phno

def get_private_phno(self):
return self.__phno

def set_private_phno(self, phno):


self.__phno = phno

customer = Bank("John Doe", "123456", "98765")


print(f"Public Name: {customer.name}")

print(f"Protected Account Number: {customer._accno}")

print(f"Private Phone numner: {customer.get_private_phno()}")

customer.set_private_phno("12345")
print(f"Update Private Phone number: {customer.get_private_phno()}")

Public Name: John Doe


Protected Account Number: 123456
Private Phone numner: 98765
Update Private Phone number: 12345

keyboard_arrow_down Question 1:

Create a class Dog with the following property as name and breed:

A public method () that displays the dog details.


class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
dog1 = Dog("Buddy", "Golden Retriever")
dog2 = Dog("Max", "Labrador")

print(f"{dog1.name} is a {dog1.breed}")
print(f"{dog2.name} is a {dog2.breed}")

keyboard_arrow_down Question 1:

Create a class Employee with the following property as Ie,namer,department,salary:

A public method calculate salary() that calculate the salary if bonsu and overtime hours details are given.

class Employee:
def __init__(self,employee_id,name,department,basic_salary):
self.employee_id=employee_id
self.name=name
self.department=department
self.basic_salary=basic_salary
def calculate_salary(self,bonus=0,overtime_hour=0):
total_salary=self.basic_salary+bonus+overtime_pay
return total_salary
def calculate_salary(self,bonus=0,overtime_hours=0):
overtime_pay=overtime_hours*750
total_salary=self.basic_salary+bonus+overtime_pay
return total_salary
def display_info(self):
print(f"employee id:{self.employee_id}")
print(f"name:{self.name}")
print(f"department:{self.department}")
print(f"basic salary:{self.basic_salary}")
employee=Employee(101,"pallavi","it",59900)
employee.display_info()
print("total salary (basic only):",employee.calculate_salary())
print("total salary (with bonus):",employee.calculate_salary(bonus=7999))
print("total salary (with bonus and overtime):",employee.calculate_salary(bonus=7999,overtime_hours=10))

keyboard_arrow_down Question 1:

Create a class SMS with the following property as source1 as public, source2 as protected,source3 as private:

A public method get_source3 that displays the private attribute details.

class Sms:
def __init__(self,source1,source2,source3):
self.source1 = source1
self._source2 = source2
self.__source3 = source3

def display_info(self):
print(f" source1 is {self.source1} ")
print(f" source2 is {self._source2} ")
print(f" source3 is {self.__source3} ")

def get_source2(self):
return self._source2

obj1 = Sms("Whatsapp","Instagram","Facebook")
obj1.display_info() #calling the display_info method
print("using object and getter calling source2:",obj1.get_source2())
# print(obj1.__source3)
print("using object and calling attribute source3:",obj1._Sms__source3) #using name mangling access private attribute
dictionary = obj1.__dict__
print(dictionary)

source1 is Whatsapp
source2 is Instagram
source3 is Facebook
using object and getter calling source2: Instagram
using object and calling attribute source3: Facebook
{'source1': 'Whatsapp', '_source2': 'Instagram', '_Sms__source3': 'Facebook'}

keyboard_arrow_down Question 1:

Create a class Book with the following property as title,year,author_name:

A public method display_book_details() that displays the book details.


class book:
no_of_books = 0

def __init__(self,title,author,year):
self.title = title
self.author = author
self.year = year
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

@classmethod
def get_no_of-books_created(cls):
return cls.no_of_books

book1 = book("1984","george orwell",1200)


book2 = book("too kill","hap",800)
book1.display_book_details()
book2.display_book_details()

keyboard_arrow_down Question 1:

Define an init() method to initialize the title, author and price attributes

display_book_details(): an instance method that displays the attribute of the book

validate_price(): a static method to check if price entered is valid or not( non-negative and greater than zero)

Check_if_discount_available(): an instance method which will return True if discount is available else False.[ Condition : price > 999 then
discount is available else no discount]

class book:
def __init__(self,title,author,price):
self.title=title
self.author=author
self.price=price
def display_book_details(self):
print(f"title:(self.title),author:(self.author),price(self.price)")
def validate_price(self):
if price>0:
return self.value
def check_if_discount_available(self,value):
if value>999:
return true
else:
return false
my_book1=book("the wanderer","charles",950)
my_book2=book("the lost child","philies",1050)
my_book1.display_book_details()
my_book2.display_book_details()

class Bank:
def__init__(self, name, accno, phno)
self.name = name
self._accno = accno
self.__phno = phno
def get_private_phno(self):
return self._phno
def private_phno(self):
return self.__phno
bank1 = Bank("chitra","123456","9980294506")
print(f"Name:{bank1.name}")
print(f"Account Number: {bank1._accno}")
print(f"Phone Number: {bank1.get_private__phno()}")
print(f"Phone Number(using mangled name): {bank1._Bank_phno}")
print(f"Phone Number(using decorator property): {bank1.private_phno}")

class Vehicle:
vehicle_count=0
def __init__(self):
Vehicle.vehicle_count +=1
@classmethod
def number_of_vehicles(cls):
return cls.vehicle_count
class Car(Vehicle):
def __init__(self):
super(Car,self).__init__()
class Bike(Vehicle):
def __init__(self):
super(Bike,self).__init__()
car1=Car()
car2=Car()
bike1=Bike()
print("number of vehicles:", Vehicle.number_of_vehicles())

number of vehicles: 3

class shape:
def areaofcircle(self,r):
pi=3.14
self.area=pi*r*r
def areaofrectangle(self,len,ber):
self.area = len*ber
class circle(shape):
def areaofcircle(self,r):
self.r=r
super().areaofcircle(self.r)
print("area of circle",self.area)
class rect(shape):
def areaofrectangle(self,len,ber):
super().areaofrectangle(len,ber)
print("area of rectangle",self.area)
circle1=circle()
rect1=rect()
circle1.areaofcircle(4)
rect1.areaofrectangle(2,4)

class Employee:
def __init__(self,name,salary):
self.name=name
self.salary=salary
class Manager(Employee):
def __init__(self,name,salary,department):
super().__init__(name,salary)
self.department=department
obj1=Manager("VISHNU",100000,"Dev")
print(f"MANAGER:{obj1.name} \nSALARY:{obj1.salary} \nDEPARTMENT:{obj1.department}")

keyboard_arrow_down Question 1

Demonstrate a Python program to define a class Parrot with attributes name and age, create two objects of the class (parrot1 and parrot2),
assign values to their attributes, and access the attributes

class parrot:
name = " "
age = 0
parrot1=parrot()
parrot1.name="blu"
parrot1.age=12
parrot2=parrot()
parrot2.name="may"
parrot2.age=10
print(f"i am {parrot1.name} my age is {parrot1.age} ")
print(f"i am {parrot2.name} my age is {parrot2.age} ")

class Book:
def __init__(self,title,author,publisher,price):
self.title=title
self._author=author
self.__publisher=publisher
self.price=price
print(f"Title : {self.title}")
print(f"Author : {self._author}")
print(f"Publisher : {self._Book__publisher}")
print(f"Price : {self.price}")
Book1=Book("Avenergs","Stan Lee","Marvel",499)
class College:
def __init__(self,name):
self.__name=name
print(f"Name : {self._College__name}")
Presidency=College("Harish")
print(f"Name : {Presidency._College__name}")

Name : Harish
Name : Harish

class Employee:
company="Tech Corp"
def __init__(self,emp_id,name,salary):
self.__emp_id=emp_id
self.__name = name
self.salary=salary
def display_info(self):
print(f"company : {self.company}")
print(f"emp_id : {self.__emp_id}")
print(f"name : {self.__name}")
print(f"salary : {self.salary}")
def get(self):
return (self.__emp_id)
return (self.__name)
def set(self,name):
self.__name = name
employee1=Employee(1,"Nitin",150000)
employee2=Employee(2,"samarth",150000)
employee1.display_info()
employee2.display_info()

company : Tech Corp


emp_id : 1
name : Nitin
salary : 150000
company : Tech Corp
emp_id : 2
name : samarth
salary : 150000

class Employee:
company="Tech Corp"
def __init__(self,emp_id,name,salary):
self.__emp_id=emp_id
self.__name = name
self.salary=salary
def display_info(self):
print(f"company : {self.company}")
print(f"emp_id : {self.__emp_id}")
print(f"name : {self.__name}")
print(f"salary : {self.salary}")
def get(self):
return (self.__emp_id),(self.__name)
def set(self,name):
self.__name = name
employee1=Employee(1,"Nitin",150000)
employee2=Employee(2,"samarth",150000)
employee1.display_info()
employee2.display_info()
employee1.get()[1] + " & " + employee2.get()[1]

company : Tech Corp


emp_id : 1
name : Nitin
salary : 150000
company : Tech Corp
emp_id : 2
name : samarth
salary : 150000
'Nitin & samarth'

keyboard_arrow_down Question 2:

Demonstrate the functionality of the Bank class by creating an instance of the class(name,accno,phno), and showcase how to access its public,
private, and protected attributes.

class Bank:
def __init__(self,name,accno,phno):
self .name = name
self._accno = accno
self.__phno = phno
def get_phno(self):
return self.__phno

def set_phnoe(self,new_phno):
self.__phno = new_phno
print("phnoe number update successfully!")

customer = Bank("varun", "9945599211","935-3889")


print("public Attribute (name):",customer.name)
print("protected Attribute (Account number):",customer._accno

try:
print("private Attribute (phone number):",customer.__phno)
except AttributeError as e:
print("f Error accessing private attribute directly: {e}")

print("accessing private Attribute via method:", customer.get_phone())

customer.set_phone("935-3889")
print("modified private Attribute via method:", customer.get_phone())

class employee:
def __init__(self,id,name,dept,salary,bouns=0,ot_hours=0):
self.id = id
self.name = name
self.dept = dept
self.salary = salary
self.bouns = bouns
self.ot_hours = ot_hours
def total_salary(self):
ot_pay = self.ot_hours = 750
return self.salary + self.bouns + ot_pay
emp1 = employee(1,"abc","hr",68979)
emp2 = employee(2,"hjl""bhm",79876,bouns=897098)
emp3 = employee(3,"sam","finance",87687,ot_hours+12)
print(emp1.total_salary())
print(emp2.total_salary())
print(emp3.total_salary())

class Student:
def __init__(self,name,__regno):
self.__name=name
self.__regno=regno
def get_student(name):
return self.__name
def get_student(regno):
return self.__regno
student1=Student()
student1.get_student(self)
print(f"student name is{self.__name}")

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-64-f17f4347d16a> in <cell line: 9>()
7 def get_student(regno):
8 return self.__regno
----> 9 student1=Student()
10 student1.get_student(self)
11 print(f"student name is{self.__name}")

TypeError: Student.__init__() missing 2 required positional arguments: 'name' and '_Student__regno'

class User:
def __init__(self,name,username,bio):
self.name = name
self.username = username
self.bio = bio

def display_profile(self):
print(f" The Name of user is {self.name} ")
print(f" his/her Username as {self.username} ")
print(f" The Bio is {self.bio} ")

obj1 = User("ravan" , "r_a_v_a_n" , "i am from bangalore , and i am working as a software Enginear at Abc Company")
obj1.display_profile()

keyboard_arrow_down Question for Bank Class using @property decorator as a getter method
class Bank:
def __init__(self,name,accno,phno):
self.name=name
self.accno=accno
self.phno=phno

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))==1 and str(value).isdigit():
self._phno=value
else:
raise valueError("Phone must contain 10 digits")

bank_account=Bank("Thanu","123","9880181668")
print(f"Name:{bank_account.name}")
print(f"Accno:{bank_account.accno}")
print(f"phno(instance method):{bank_account._bank_phno()}")
print(f"phno:{bank_account.private_phno}")
bank_account.priavte_phno="9880912366"
print(f"updated:{bank_account.private_phno}")

keyboard_arrow_down Inheritance
class Employee:
def __init__(self,name,salary):
self.__name=name
self.__salary=salary
def display_info(self):
print(f"Name: {self.__name} and Salary: {self.__salary}")

class Manager(Employee):
def __init__(self,name,salary,department):
super().__init__(name,salary)
self.department=department
def display_info(self):
super().__display_info(name,salary)
print(f"department: {self.department}")

Employee=("Mary",30000,"IT")
Employee.display_info()
Manager.display_info()

class Shape:
def __init__(self):
self.area=0

def calculation_area(self):
return self.area

class Circle(Shape):
def __init__(self,radius):
super().__init__()
self.radius = radius
def calculate_area(self):
self.area = 3.14*self.radius*self.radius
print(self.area)

class rectangle(Shape):
def __init__(self,length,width):
super().__init__()
self.length=length
self.width=width

def calculate_area(self):
self.area = self.length*self.width
print(self.area)
obj = rectangle(20,24)
obj.calculate_area()
obj2 = Circle(4)
obj2.calculate_area()

keyboard_arrow_down Question 2:
Explain how to use super() keyword and how method overriding in Inheritance works by using the class named as Person as parent with
attributes name,gender and age.

Create an child class Employee with attributes emp_id, salary .Create a method display_info() which is already present in parent and verify
method overriding.

class Person:
def __init__(self,name,gender,age):
self.name=abc
self.gender=gender
self.age=age
def display_info(self):
print(self.name)
print(self.gender)
print(self.age)

class Employee(Person):
def __init__(self,name,gender,age,emp_id,salary):
super().__init__(name,gender,age)
self.emp_id=emp_id
self.salary=salary
def display_info(self):
super().display_info()
print(self.emp_id)
print(self.salary)

obj1=Employee(2020,10000)
obj1.display_info()

class ParentClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2

def some_method(self):
print("This is a method in the parent class")

class ChildClass(ParentClass):
def __init__(self, attribute1, attribute2, attribute3):
super().__init__(attribute1, attribute2)
self.attribute3 = attribute3

def some_method(self):
super().some_method()
print("This is a method in the child class and it overrides the parent class method")

# Example usage
child = ChildClass("value1", "value2", "value3")
child.some_method()

keyboard_arrow_down Question 1:

Create a base class Shape and derived classes Circle and Rectangle.

The Shape class should have a method to calculate area (default to 0). The Circle class should inherit from Shape and have an attribute for the
radius. The Rectangle class should inherit from Shape and have attributes for length and width. Formula :

circle : 3.14 X radius X radius

rectangle : length X breadth

class Shape:
def __init__(self,name,area=0):
self.name=name
self.area=area
def calculate_area(self):
pass
class Circle(Shape):
def __init__(self,name,radius):
super().__init__(name)
self.radius=radius
def calculate_area(self,radius):
super().calculate_area()
self.area=3.14*radius*radius
print(f"The Shape is {self.name} and area of the circle is {self.area}cm ")
class Rectangle(Shape):
def __init__(self,name,length,width):
super().__init__(name)
self.length=length
self.width=width
def calculate_area(self,length,width):
super().calculate_area()
self.area=length*width
print(f"The Shape is {self.name} The area of the rectangle is {self.area}cm")
circle=Circle("Circle",2)
circle.calculate_area(2)
rectangle=Rectangle("Rectangle",2,3)
rectangle.calculate_area(2,3)

keyboard_arrow_down Question 1:

Demostrate inheritance using Animal as parent and Dog as child class and use the super keyword and show overriding.

class Animal:
def __init__(self,name,age,color):
self.name=name
self.age=age
self.color=color

def display_info(self):
print(f"Name :{self.name},Age :{self.age},Color :{self.color}")

class Dog(Animal):
def __init__(self,name,age,color):
# self.name=name
# self.age=age
# self.color=color
super().__init__(name,age,color)

def display_info(self):
super().display_info()
# print(f"Name :{self.name},Age :{self.age},Color :{self.color}")
# print(super().{self.name}, super().{self.age}, super().{self.color})

d=Dog("Tommy",5,"Brown")
d.display_info()

keyboard_arrow_down Question 2:

Explain how to use super() keyword and how method overriding in Inheritance works by using the class named as Person as parent with
attributes name,gender and age.

Create an child class Employee with attributes emp_id, salary .Create a method display_info() which is already present in parent and verify
method overriding.

class Person:
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age

def display_info(self):
return f"Name: {self.name}, Gender: {self.gender}, Age: {self.age}"

class Employee(Person):
def __init__(self, name, gender, age, emp_id, salary):
super().__init__(name, gender, age) # Calling the parent class constructor
self.emp_id = emp_id
self.salary = salary

def display_info(self):
person_info = super().display_info() # Calling the parent class method
return f"{person_info}, Employee ID: {self.emp_id}, Salary: {self.salary}"

emp1 = Employee("Alice", "Female", 30, "E123", 50000)

print(emp1.display_info())

keyboard_arrow_down Question 1:

Explain how to use super() keyword and how method overriding in Inheritance works by using the below class.

Define an init() method to initialize these attributes.

# What is the ERROR in the below code ? How do you FIX it??
class BaseClass:
def __init__(self,attribute1,attribute2):
self.attribute=attribute1
self.attribute2=attribute2

class DerivedClass(BaseClass):
def__init__(self,attribute1,attribute2)
super().__init(attribute1,attribute2)
def some_method(self):
print("THIS IS THE OVERIDDEN METHOD")

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-bb88a85adbf2> in <cell line: 6>()
4 self.attribute2=attribute2
5
----> 6 class DerivedClass(BaseClass):
7 def__init__(self,attribute1,attribute2)
8 super().__init(attribute1,attribute2)

<ipython-input-1-bb88a85adbf2> in DerivedClass()
5
6 class DerivedClass(BaseClass):
----> 7 def__init__(self,attribute1,attribute2)
8 super().__init(attribute1,attribute2)
9 def some_method(self):

NameError: name 'def__init__' is not defined

keyboard_arrow_down Abstraction
keyboard_arrow_down Question 1:

Write a Python program that demonstrates abstraction by creating an abstract class Shape with 2 abstract methods area() and perimeter().

Then, implement two concrete classes Circle and Rectangle that inherit from Shape and compute the area and perimeter for each.

Instantiate the Circle and Rectangle classes and display the area and perimeter for each shape.

from abc import ABC,abstractmethod


class Shape(ABC):
@abstractmethod
def perimeter(self):
pass
@abstractmethod
def area(self):
pass

class Circle(Shape):
def __init__(self,radius):
self.radius=radius
def perimeter(self):
return 2*3.14*self.radius
def area(self):
return 3.14*self.radius**2
class Rectangle(Shape):
def __init_self(self,length,breadth):
self.length=length
self.breadth=breadth
def perimeter(self):
return 2*(self.length+self.breadth)
def area(self):
return self.length*self.breadth

keyboard_arrow_down Question 1:

Write a Python program that demonstrates abstraction by creating an abstract class Vehicle with an abstract method number_of_wheels().

Then, implement two concrete classes Car and Bike that inherit from Vehicle and define the number of wheels for each.

Instantiate the Car and Bike classes and display the number of wheels for each vehicle.

class Vehicle:
def __init__(self, name, model, year):
self.name=name
self.model=model
self.year=year

def display_details(self):
print(f"Vehicle Name: {self.name}")
print(f"Model: {self.model}")
print(f"Year: {self.year}")

def update_details(self, name=None, model=None, year=None):


if name:
self.name=name
if model:
self.model=model
if year:
self.year=year

class Car(Vehicle):
def __init__(self, name, model, year, car_type):
super().__init__(name, model, year)
self.car_type=car_type
def display_details(self):
super().display_details()
print(f"Car Type: {self.car_type}")

class Truck(Vehicle):
def __init__(self, name, model, year, load_capacity):
super().__init__(name, model, year)
self.load_capacity=load_capacity

def display_details(self):
super().display_details()
print(f"Load Capacity: {self.load_capacity} tons")

car=Car("lambo", "mer", 2020, "sedan")


truck=Truck("Ford", "F-150", 2019, 2)

car.display_details()
truck.display_details()

car.update_details(name="honda", model="civic", year=2022)


truck.update_details(load_capacity=100)

print("\nUpdated Car Details:")


car.display_details

print("\nUpdated Truck Details:")


truck.display_details()

File "<ipython-input-48-b8d3f19ec63e>", line 46


print("\nUpdated Car Details:")
^
IndentationError: unexpected indent

keyboard_arrow_down Question 1:

Write a Python program that demonstrates abstraction by creating an abstract class Vehicle with an abstract method number_of_wheels().

Then, implement two concrete classes Car and Bike that inherit from Vehicle and define the number of wheels for each.

Instantiate the Car and Bike classes and display the number of wheels for each vehicle.

#FIX THE ERROR in the below code

from abc import ABC,abstractmethod


class vehicle(ABC):
def number_of_wheels(self):
pass
class car(vehicle):
def number_of_wheels(self):
return 4
class bike(vehicle):
def number_of_wheels(self):
return 2
car = car()
bike = bike()
print("number of wheels in a car:",car.number_of_wheels())
print("number of wheels in a bike:",bike.number_of_wheels())
---------------------------------------------------------------------------

keyboard_arrow_down
TypeError

11
Question 1:
<ipython-input-58-c8cb0eb4ec6e>
car = car()
Traceback (most recent call last)
in <cell line: 13>()

12 program
Write a Python bike
that=demonstrates
bike() abstraction by creating an abstract class Vehicle with an abstract method number_of_wheels().
---> 13 print("number of wheels in a car:",car.number_of_wheels())
Then, implement two concrete
14 print("number ofclasses
wheels Car
in and Bike that inherit from Vehicle and define the number of wheels for each.
a bike:",bike.number_of_wheels())

Instantiate the Car


TypeError: and Bike classes and display
car.number_of_wheels() missingthe1 number of positional
required wheels for each vehicle.
argument: 'self'

from abc import ABC,abstractmethod


#create an abstract class
class vehicle(ABC):
@abstractmethod
def number_of_wheels(self):
pass

class bike(vehicle):
def number_of_wheels(self):
print("bike has 2 wheels")

class car(vehicle):
def number_of_wheels(self):
print("car has 4 wheels")

bike1=bike()
bike2=bike()
bike3=bike()
car1=car()
car2=car()
car3=car()
bike1.number_of_wheels()
bike2.number_of_wheels()
bike3.number_of_wheels()
car1.number_of_wheels()
car2.number_of_wheels()
car3.number_of_wheels()

bike has 2 wheels


bike has 2 wheels
bike has 2 wheels
car has 4 wheels
car has 4 wheels
car has 4 wheels

vehicobjects =[bike1,bike2,bike3,car1,car2,car3]
#Runtime Polymorphism
for obj in vehicobjects:
obj.number_of_wheels() #Ducktyping

bike has 2 wheels


bike has 2 wheels
bike has 2 wheels
car has 4 wheels
car has 4 wheels
car has 4 wheels

You might also like