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

Python OOP Exercise - Classes and Objects Exercises

This document contains an object-oriented programming exercise to practice creating classes and using concepts like inheritance and polymorphism in Python. It includes 8 questions on topics like creating classes and objects, defining methods and instance variables, creating child classes that inherit from parent classes, and checking object types.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
318 views

Python OOP Exercise - Classes and Objects Exercises

This document contains an object-oriented programming exercise to practice creating classes and using concepts like inheritance and polymorphism in Python. It includes 8 questions on topics like creating classes and objects, defining methods and instance variables, creating child classes that inherit from parent classes, and checking object types.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

PYnative

Python Programming
 Learn Python  Exercises  Quizzes  Code Editor  Tricks

Home » Python Exercises » Python Object-Oriented Programming (OOP) Exercise: Classes and Objects
Posted In
Exercises
Python Python Exercises Python
Object-Oriented Programming Python Object-Oriented Programming (OOP)
(OOP) Exercise: Classes and Objects Exercises
Tweet F share in share P Pin
Updated on: December 8, 2021 | + 50 Comments

 Python Exercises
This Object-Oriented Programming (OOP) exercise aims to help you to learn and practice OOP
 Python Exercises Home concepts. All questions are tested on Python 3.
 Basic Exercise for Beginners
Python Object-oriented programming (OOP) is based on the concept of “objects,” which can
 Input and Output Exercise
contain data and code: data in the form of instance variables (often known as attributes or
 Loop Exercise
properties), and code, in the form method. I.e., Using OOP, we encapsulate related properties and
 Functions Exercise
behaviors into individual objects.
 String Exercise

 Data Structure Exercise What is included in this Python OOP exercise?

 List Exercise
This OOP classes and objects exercise includes 8 different programs, questions, and challenges. All
 Dictionary Exercise
solutions are tested on Python 3.
 Set Exercise

 Tuple Exercise This OOP exercise covers questions on the following topics:

 Date and Time Exercise


Class and Object creation
 OOP Exercise
Instance variables and Methods, and Class level attributes
 Python JSON Exercise
Model systems with class inheritance i.e., inherit From Other Classes
 Random Data Generation
Exercise Parent Classes and Child Classes

 NumPy Exercise Extend the functionality of Parent Classes using Child class
 Pandas Exercise Object checking
 Matplotlib Exercise
When you complete each question, you get more familiar with the Python OOP. Let us know if you
 Python Database Exercise
have any alternative solutions. It will help other developers.

All Python Topics Use Online Code Editor to solve exercise questions.

Python Basics Python Exercises Refer:


Python Quizzes
Python File Handling Guide on Python OOP
Python OOP
Inheritance in Python
Python Date and Time
Python Random Python Regex
Python Pandas
Python Databases Table of contents
Python MySQL
Python PostgreSQL
OOP Exercise 1: Create a Class with instance attributes
Python SQLite Python JSON
OOP Exercise 2: Create a Vehicle class without any variables and methods
OOP Exercise 3: Create a child class Bus that will inherit all of the variables and methods of the
Vehicle class
OOP Exercise 4: Class Inheritance
PYnative
Python Programming
OOP Exercise 5: Define a property that must have the same value for every class instance
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
(object)
OOP Exercise 6: Class Inheritance
OOP Exercise 7: Check type of an object
OOP Exercise 8: Determine if School_bus is also an instance of the Vehicle class

OOP Exercise 1: Create a Class with instance attributes

Write a Python program to create a Vehicle class with max_speed and mileage instance attributes.

Refer:

Classes and Objects in Python

Instance variables in Python

+ Show Solution

class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage

modelX = Vehicle(240, 18)


print(modelX.max_speed, modelX.mileage)

   Run

OOP Exercise 2: Create a Vehicle class without any variables and


methods

+ Show Solution

class Vehicle:
pass

   Run

OOP Exercise 3: Create a child class Bus that will inherit all of the
variables and methods of the Vehicle class

Given:

class Vehicle:

def __init__(self, name, max_speed, mileage):


self.name = name
self.max_speed = max_speed
self.mileage = mileage
PYnative    Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming

Create a Bus object that will inherit all of the variables and methods of the parent Vehicle class and
display it.

Expected Output:

Vehicle Name: School Volvo Speed: 180 Mileage: 12

Refer: Inheritance in Python

+ Show Solution

class Vehicle:

def __init__(self, name, max_speed, mileage):


self.name = name
self.max_speed = max_speed
self.mileage = mileage

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 180, 12)


print("Vehicle Name:", School_bus.name, "Speed:", School_bus.max_speed, "Mileage:", S

   Run

OOP Exercise 4: Class Inheritance

Given:

Create a Bus class that inherits from the Vehicle class. Give the capacity argument of
Bus.seating_capacity() a default value of 50.

Use the following code for your parent Vehicle class.

class Vehicle:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage

def seating_capacity(self, capacity):


return f"The seating capacity of a {self.name} is {capacity} passengers"

 

Expected Output:

The seating capacity of a bus is 50 passengers

Refer:
PYnative Inheritance in Python
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming
Polymorphism in Python

+ Show Hint

First, use method overriding.

Next, use default method argument in the seating_capacity() method definition of a bus
class.

+ Show Solution

class Vehicle:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage

def seating_capacity(self, capacity):


return f"The seating capacity of a {self.name} is {capacity} passengers"

class Bus(Vehicle):
# assign default value to capacity
def seating_capacity(self, capacity=50):
return super().seating_capacity(capacity=50)

School_bus = Bus("School Volvo", 180, 12)


print(School_bus.seating_capacity())

   Run

OOP Exercise 5: Define a property that must have the same value for
every class instance (object)

Define a class attribute”color” with a default value white. I.e., Every Vehicle should be white.

Use the following code for this exercise.

class Vehicle:

def __init__(self, name, max_speed, mileage):


self.name = name
self.max_speed = max_speed
self.mileage = mileage

class Bus(Vehicle):
pass

class Car(Vehicle):
pass

 

Expected Output:
PYnative  Learn
Color: White, Vehicle name: School Volvo, Speed: 180, Python
Mileage: 12  Exercises  Quizzes  Code Editor  Tricks
Python Programming
Color: White, Vehicle name: Audi Q5, Speed: 240, Mileage: 18

Refer: Class Variable in Python

+ Show Hint

Define a color as a class variable in a Vehicle class

+ Show Solution

Variables created in .__init__() are called instance variables. An instance variable’s value is
specific to a particular instance of the class. For example, in the solution, All Vehicle objects have a
name and a max_speed, but the name and max_speed variables’ values will vary depending on the
Vehicle instance.

On the other hand, the class variable is shared between all class instances. You can define a
class attribute by assigning a value to a variable name outside of .__init__() .

class Vehicle:
# Class attribute
color = "White"

def __init__(self, name, max_speed, mileage):


self.name = name
self.max_speed = max_speed
self.mileage = mileage

class Bus(Vehicle):
pass

class Car(Vehicle):
pass

School_bus = Bus("School Volvo", 180, 12)


print(School_bus.color, School_bus.name, "Speed:", School_bus.max_speed, "Mileage:", S

car = Car("Audi Q5", 240, 18)


print(car.color, car.name, "Speed:", car.max_speed, "Mileage:", car.mileage)

   Run

OOP Exercise 6: Class Inheritance

Given:

Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle is
seating capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as a
maintenance charge. So total fare for bus instance will become the final amount = total fare +
10% of the total fare.

Note: The bus seating capacity is 50. so the final fare amount should be 5500. You need to override
the fare() method of a Vehicle class in Bus class.
PYnative Use the following code for your parent Vehicle class. We need to access the parent class from inside
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming
a method of a child class.

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 12, 50)


print("Total Bus fare is:", School_bus.fare())

 

Expected Output:

Total Bus fare is: 5500.0

+ Show Solution

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100

class Bus(Vehicle):
def fare(self):
amount = super().fare()
amount += amount * 10 / 100
return amount

School_bus = Bus("School Volvo", 12, 50)


print("Total Bus fare is:", School_bus.fare())

   Run

OOP Exercise 7: Check type of an object

Write a program to determine which class a given Bus object belongs to.

Given:

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
PYnative self.capacity = capacity
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming
class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 12, 50)

 

+ Show Hint

Use Python’s built-in function type() .

+ Show Solution

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 12, 50)

# Python's built-in type()


print(type(School_bus))

   Run

OOP Exercise 8: Determine if School_bus is also an instance of the


Vehicle class

Given:

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 12, 50)

 

+ Show Hint

Use isinstance() function


PYnative + Show Solution  Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 12, 50)

# Python's built-in isinstance() function


print(isinstance(School_bus, Vehicle))

   Run

Filed Under: Python , Python Exercises , Python Object-Oriented Programming (OOP)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create
free Python resources.

Tweet F share in share P Pin

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to


write articles to help students, developers, and learners. Follow me on Twitter

Related Tutorial Topics:

Python Python Exercises Python Object-Oriented Programming (OOP)

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

15+ Topic-specific Exercises and Quizzes


Exercises Quizzes
Each Exercise contains 10 questions
Each Quiz contains 12-15 MCQ

Comments
PYnative Kavindu says
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming A U G U S T 1 9 , 2 0 2 3 AT 3 : 4 5 P M

class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage

def seating_capacity(self, capacity):


return f”The seating capacity of a {self.name} is {capacity} passenger”

class Vehicle:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage

def seating_capacity(self, capacity):


return f”The seating capacity of a {self.name} is {capacity} passengers”

class Bus(Vehicle):
# assign default value to capacity
def seating_capacity(self, capacity=50):
return super().seating_capacity(capacity=50)

class Vehicle:
# Class attribute
colour = “White”

def __init__(self, name, max_speed, mileage):


self.name = name
self.max_speed = max_speed
self.mileage = mileage

class Bus(Vehicle):
pass

class Car(Vehicle):
pass

School_bus = Bus(“School Volvo”, 180, 12)


print(School_bus.colour, School_bus.name, “Speed:”, School_bus.max_speed, “Mileage:”,
School_bus.mileage)

car = Car(“Audi Q5”, 180, 18)


print(car.colour, car.name, “Speed:”, car.max_speed, “Mileage:”, car.mileage)

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100
PYnative class Bus(Vehicle):
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming
def fare(self):
return 1.1*self.capacity*100

School_bus = Bus(“School Volvo”, 12, 50)


print(“Total Bus fare is:”, School_bus.fare())
REPLY

Driss Fadal says


A U G U S T 2 , 2 0 2 3 AT 4 : 1 4 A M

from pyexpat import model

color = “white”
capacity = 1
fare = capacity * 100

class Vehicle:
def __init__(self, name, max_speed, mileage, capacity):
self.max_speed = max_speed
self.mileage = mileage
self.name = name
self.capacity = capacity

def fare(self):
return self.capacity * 100

model1x = Vehicle(“Toyota”, 240, 23000, 5)

class Bus(Vehicle):
def __init__(self, name, max_speed, mileage, capacity):
super().__init__(name, max_speed, mileage, capacity)

def fare(self):
#return Vehicle.fare(self) * 10 / 100 + Vehicle.fare(self) or
amount = super().fare()
amount += amount * 10 / 100
return amount

bus1 = Bus(“daf”, 149, 33000, 50)


# bus_fare = bus1.fare()
# print(f”total bus fare is :${int(bus_fare*(10/100)+bus_fare)}”)

print(bus1.fare())

REPLY

Mokhtar Mahmoudian says


M A R C H 4 , 2 0 2 3 AT 1 2 : 0 6 A M

#Exercise 3

class Vehicle:
PYnative def __init__(self ,Max_speed, Mileage):
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming

self.Max_speed = Max_speed

self.Mileage = Mileage

Bus = Vehicle(180, 12)

print("vehicle name : school volvo","\n", "speed : ",

Bus.Max_speed,"\n", "Mileage :", Bus.Mileage)


REPLY

Adrian says
F E B R U A R Y 2 8 , 2 0 2 3 AT 1 0 : 1 0 P M

About exercise 4:
in line -> return super().seating_capacity(capacity=50)

I think it should be -> return super().seating_capacity(capacity)

If we set 50 in a method call, then it will be impossible to set different parameters.


For example, if we call:
b = Bus('bus', 80, 1000)

print(b.seating_capacity(30)) -> output will be 50

REPLY

Reef says
O C T O B E R 1 1 , 2 0 2 3 AT 1 : 4 7 A M

Yes indeed. It should be -> return super().seating_capacity(capacity)


which will allow for setting a value for capacity as in: -> b.seating_capacity(120)

REPLY

Dealer says
J A N U A R Y 2 0 , 2 0 2 3 AT 7 : 2 8 P M

Exercise 7, is this a good practice?

class Vehicle:

def __init__(self, name, mileage, capacity):

self.name = name

self.mileage = mileage

self.capacity = capacity
PYnative  Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming
class Bus(Vehicle):

@staticmethod

def which_class():

return __class__.__name__

School_bus = Bus("School Volvo", 12, 50)

print(School_bus.which_class())
REPLY

ayoub says
J A N U A R Y 2 2 , 2 0 2 3 AT 1 1 : 2 1 P M

Write a function to calculate resistance and capacitance (i.e. the function takes
current and voltage as data and returns resistance and capacitance)
Solve it

REPLY

Utkarsh Dadaso Salunkhe says


F E B R U A R Y 2 3 , 2 0 2 3 AT 9 : 5 5 P M

class circuit:

def __init__(self,voltage,current):

self.voltage=voltage

self.current= current

def resistance(self):

return self.voltage/ self.current

def capacitance(self):

return self.voltage/(self.current * 2 * 3.14159265359 )

a= circuit(20,9)

r=a.resistance()

c= a.capacitance()

print(f”resistance is {r} ohms and capacitance is {c} f.”)


PYnative REPLY
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming

Dealer says
J A N U A R Y 2 0 , 2 0 2 3 AT 6 : 5 8 P M

Exercise 5 without a class variable, only with instance variable:

class Vehicle:

def __init__(self, name, max_speed, mileage):

self.color = "White"

self.name = name

self.max_speed = max_speed

self.mileage = mileage

def __str__(self):

return f"Color: {self.color}, Vehicle name: {self.name}, Speed:


{self.max_speed}, Mileage: {self.mileage}"

class Bus(Vehicle):

pass

class Car(Vehicle):

pass

bus = Bus("School Volvo", 180, 12)

car = Car("Audi Q5", 240, 18)

print(bus)

print(car)

REPLY

LUQMAN HAQIM says


N O V E M B E R 1 3 , 2 0 2 2 AT 9 : 2 4 P M

Kindly check and see if I would encounter any problems using this approach.

class vehicle:
PYnative  Learn Python  Exercises  Quizzes  Code Editor  Tricks
Python Programming
color="white"

def __init__(self,name,max_speed,mileage,capacity):

self.name=name

self.max_speed=max_speed

self.milage=mileage

self.capacity=capacity

def fare(self):

fare= self.capacity*100

totalFare= fare + (10/100*fare)

return totalFare

def desc_vehicle(self):

print(f"Color:{self.color} Vehicle Name: {self.name} Speed:


{self.max_speed} Mileage: {self.milage} ")

class bus(vehicle):

pass

class car(vehicle):

pass
REPLY

Karan says
J A N U A R Y 6 , 2 0 2 3 AT 1 2 : 1 8 P M

class vehicle:

color="white"

def __init__(self,name,max_speed,mileage,capacity):

self.name=name

self.max_speed=max_speed

self.milage=mileage
PYnative
Python Programming
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
self.capacity=capacity

def fare(self):

fare= self.capacity*100

totalFare= fare + (10/100*fare)

return totalFare

def desc_vehicle(self):

print(self.capacity,"is capacity",self.name,"is
name",self.max_speed,"speed",self.milage, "milage",self.capacity,
"capacity")

class bus(vehicle):

pass

class car(vehicle):

pass

a=car(80,"ko",64,32)

a.desc_vehicle()
REPLY

Ankit Shukla says


S E P T E M B E R 2 0 , 2 0 2 2 AT 1 2 : 3 7 P M

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100

class Bus(Vehicle):
def __init__(self, name, mileage, capacity = 50):
super().__init__(name, mileage, capacity)

def fare(self):
fare = super().fare()
# this is bus so we need to add an extra 10% on full fare as a maintena
total_fare = fare + (fare*0.10)
return total_fare
PYnative
Python Programming School_bus = Bus("School Volvo", 12)  Learn Python  Exercises  Quizzes  Code Editor  Tricks
print("Total Bus fare is:", School_bus.fare())

REPLY

Ankit Shukla says


S E P T E M B E R 2 0 , 2 0 2 2 AT 1 2 : 3 5 P M

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100

class Bus(Vehicle):
def __init__(self, name, mileage, capacity = 50):
super().__init__(name, mileage, capacity)

def fare(self):
fare = super().fare()
# this is bus so we need to add an extra 10% on full fare as a maintena
total_fare = fare + (fare*0.10)
return total_fare

School_bus = Bus("School Volvo", 12)


print("Total Bus fare is:", School_bus.fare())

REPLY

Sherrif says
D E C E M B E R 4 , 2 0 2 2 AT 4 : 3 6 P M

This is good approach, clean code, good practice.

REPLY

Sunny says
J U L Y 2 8 , 2 0 2 2 AT 5 : 1 4 P M

class Vehicle:
color='white'
def __init__(self, name='', max_speed='', mileage=''):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
def seatingcapacity(self):
print('seating capacity of {} is {}'.format(self.name,self.capacity))
def display(self):
print('Vehicle Name:{}'.format(self.name),
'Max Speed:{}'.format(self.max_speed),
'Mileage:{}'.format(self.mileage),
'Color:{}'.format(self.color))
def fare(self):
PYnative
Python Programming
print("The fare for {} is {}".format(self.name, int(self.capacity)*100)
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
def belongs(self):
print(self.__class__.__name__)

def checkins(self):
print('Instance of Vehicle:{}'.format(isinstance(self,Vehicle)))

class Bus(Vehicle):

def __init__(self,capacity='',**kwargs):
self.capacity=capacity
super().__init__(**kwargs)
def fare(self):
print("The fare for {} is {}".format(self.name, int(self.capacity)*100

class Car(Vehicle):

def __init__(self,capacity='',**kwargs):
self.capacity=capacity
super().__init__(**kwargs)

# Example Input:
a={'name':'Volvo',
'max_speed':30,
'mileage':40,
'capacity':100}
b={'name':'Volkswagon',
'max_speed':50,
'mileage':100,
'capacity':30}
c=Bus(**a)
d=Car(**b)
c.display()
c.seatingcapacity()
c.fare()
c.belongs()
c.checkins()
d.display()
d.seatingcapacity()
d.fare()
d.belongs()
d.checkins()

OUTPUT:

Vehicle Name:Volvo Max Speed:30 Mileage:40 Color:white


seating capacity of Volvo is 100
The fare for Volvo is 11000
Bus
Instance of Vehicle:True
Vehicle Name:Volkswagon Max Speed:50 Mileage:100 Color:white
seating capacity of Volkswagon is 30
The fare for Volkswagon is 3000
Car
Instance of Vehicle:True

REPLY

Fabrizio says
J U L Y 7 , 2 0 2 2 AT 5 : 4 5 P M
PYnative
Python Programming
An alternative way of doing exercise 6:
 Learn Python  Exercises  Quizzes  Code Editor  Tricks

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self, offset=None):


offset = offset or 0
return (self.capacity + ((self.capacity*offset)/100)) * 100

class Bus(Vehicle):
def fare(self):
return super().fare(10)

School_bus = Bus("School Volvo", 12, 50)


print("Total Bus fare is:", School_bus.fare())

REPLY

Lawrence says
J U L Y 1 , 2 0 2 2 AT 1 2 : 0 9 P M

I have this example.6 I was wondering if it is correct too?

# 6
class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100

class Bus(Vehicle):
def fare(self):
return 1.1*self.capacity*100

School_bus = Bus("School Volvo", 12, 50)


print("Total Bus fare is:", School_bus.fare())

REPLY

avi says
J U L Y 6 , 2 0 2 2 AT 7 : 1 3 P M

this solution is not good because :


in the question, we are asked to add 10% to the total fare which comes from the
superclass Vehicle, so when you do
return 1.1*self.capacity*100
the total is not based on Vehicle and if I change 100 in Vehicle, it will not change in
Bus
you need to use super() so that the Total is taken from Vehicle, and then you add
PYnative
Python Programming
the 10%
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
you can do something like

class Bus(Vehicle):
def fare(self):
return super().fare() * 1.1

this will allways use the total from Vehicle and add 10% , so if we change the 100
in Vehicle, it will calculate the 10% based on the new total.

Hope that was clear, sorry if the exemples were not good
REPLY

Hanna Damarjian says


J U N E 2 9 , 2 0 2 2 AT 1 : 1 0 A M

Exercise 6 Alternative Code:

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100

class Bus(Vehicle):

def fare(self):
return super().fare() + 0.10*super().fare()

School_bus = Bus("School Volvo", 12, 50)


print("Total Bus fare is:", School_bus.fare())

REPLY

Cyrus says
M AY 1 2 , 2 0 2 2 AT 1 2 : 3 3 A M

Will I run into any problems if I just did this for Ex. 4?

class Vehicle:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage

def seating_capacity(self, capacity):


return f"The seating capacity of a {self.name} is {capacity} passengers

bus = Vehicle("bus", 0, 0)
bus.seating_capacity(50)

REPLY
PYnative
Python Programming
Suraj says
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
M AY 2 0 , 2 0 2 2 AT 8 : 3 5 P M

Call the function as print(bus.seating_capacity(50))


output:
The seating capacity of a bus is 50 passengers

NO problem!

REPLY

Masha says
A P R I L 2 3 , 2 0 2 2 AT 1 : 1 0 P M

class Vehicale():
def __init__(self,name,mileage , seat_capacity):
self.name = name
self.mileage = mileage
self.seat_capacity=seat_capacity
def fare(self):
return self.seat_capacity *100

is it correct? it does work but ..


class Bus(Vehicale):
def __init__(self,name,mileage, seat_capacity):
super().__init__(name,mileage,seat_capacity)
def fare(self):
return self.seat_capacity * 100+(self.seat_capacity * 100)*10/100

School_bus = Bus("School Volvo", 12, 50)


print("Total Bus fare is:", School_bus.fare())

REPLY

abc says
A P R I L 2 0 , 2 0 2 2 AT 8 : 3 2 A M

Thanks a ton for the well-curated structure.

REPLY

Daniel says
M A R C H 1 7 , 2 0 2 2 AT 5 : 1 4 P M

For exercise 6 I don’t know if this is good code, code but it works well!!

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100

class Bus(Vehicle):
def fare(self):
PYnative
Python Programming
return self.capacity * 110
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
School_bus = Bus("School Volvo", 12, 50)
print("Total Bus fare is:", School_bus.fare())

REPLY

Ganymehdi says
A P R I L 1 3 , 2 0 2 2 AT 1 : 0 6 A M

I had the same idea, but I think the key is that since bus fare depends on vehicle
fare, if the formula for vehicle changes (while bus remains +10% of vehicle fare)
and you need to update your code base, the change propagates without having to
modify both classes

REPLY

Cyrus says
M AY 1 3 , 2 0 2 2 AT 1 2 : 5 2 A M

Wouldn’t the code used in the solution also change if the Vehicle formula
changes? In other words, doesn’t the code below also depend on the
vehicle fare because it’s still inheriting the Vehicle’s “fare” instance

class Bus(Vehicle):
def fare(self):
amount = super().fare()
amount += amount * 10 / 100
return amount

REPLY

Nagimesi Khatwiibu Shuaibu says


M A R C H 3 , 2 0 2 2 AT 9 : 5 4 P M

very good codes

REPLY

Raji says
M A R C H 1 , 2 0 2 2 AT 5 : 0 8 P M

Very useful. I started learning python. please let me know if you have more excercise like
this. Thanks for your effort.

REPLY

Suraj Thapa says


J A N U A R Y 3 1 , 2 0 2 2 AT 5 : 0 2 A M

Thank you very much.

REPLY
PYnative
Python Programming
Jitendra chandra says
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
D E C E M B E R 2 9 , 2 0 2 1 AT 8 : 3 9 A M

Thanks a lot Brother !

REPLY

Lilit Grigoryan says


N O V E M B E R 1 1 , 2 0 2 1 AT 3 : 1 6 P M

Thank’s a lot, I enjoyed the tasks.

REPLY

Vishal says
N O V E M B E R 1 4 , 2 0 2 1 AT 1 1 : 0 9 A M

You’re welcome, Lilit.

REPLY

Saikiran Tangudu says


D E C E M B E R 3 0 , 2 0 2 1 AT 1 1 : 2 8 A M

HI Vishal please post more questions on oops

REPLY

knotJ says
O C T O B E R 1 8 , 2 0 2 1 AT 8 : 1 4 P M

Thanks. learnt lots

REPLY

Jokunsoo says
J U L Y 9 , 2 0 2 1 AT 5 : 2 8 P M

found a cleaner method for exercise 7

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity
def qclass(self):
objclass=str(type(self))
method,clss=objclass.split(".")
objclassclean=clss.replace("'>",'')
print (objclassclean)

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 12, 50)


PYnative
Python Programming
Transit_bus = Vehicle("Tesla van", 12000, 2)
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
Transit_bus.qclass()

REPLY

Abhay Kumar Mishra says


M AY 1 9 , 2 0 2 1 AT 4 : 0 2 P M

Ans_3:

class Vehicle:

def __init__(self, name, max_speed, mileage):


self.name = name
self.max_speed = max_speed
self.mileage = mileage
class Bus(Vehicle):

def __init__(self,name,max_speed, mileage):


super().__init__(name,max_speed,mileage)
def bus_info(self):
return f'school bus {self.name} maxspeed:{self.max_speed} mileage: {sel

school_bus = Bus('Volvo',180,12)
print(school_bus.bus_info())

REPLY

Mr. Lulz says


A P R I L 2 6 , 2 0 2 1 AT 4 : 2 2 A M

This was a fun exercise!

REPLY

vish says
A P R I L 1 9 , 2 0 2 1 AT 3 : 1 1 P M

That was interesting overview.. I am searching more though for oop…

Thanks for support…

REPLY

dhruv says
A P R I L 1 4 , 2 0 2 1 AT 6 : 1 4 P M

thank you vishal sir it’s very help me

REPLY

Vishal says
A P R I L 1 6 , 2 0 2 1 AT 7 : 5 4 P M
PYnative
Python Programming
I am glad it helped you, Dhruv.
 Learn Python  Exercises  Quizzes  Code Editor  Tricks

REPLY

Etra Arte says


M A R C H 1 9 , 2 0 2 1 AT 1 2 : 1 3 A M

Thank you very much Vishal, it’s a very instructive challenge

REPLY

Vishal says
M A R C H 2 1 , 2 0 2 1 AT 1 1 : 2 5 A M

I am glad it helped you.

REPLY

Emmanuel Bett says


F E B R U A R Y 1 5 , 2 0 2 1 AT 1 1 : 1 7 P M

thank you…Awesome learning experience

REPLY

Lamhamdi says
J A N U A R Y 3 1 , 2 0 2 1 AT 1 1 : 0 4 P M

Exercise Question 6: Class Inheritance

class Vehicle:
def __init__(self, name, mileage, capacity):
self.name = name
self.mileage = mileage
self.capacity = capacity

def fare(self):
return self.capacity * 100

class Bus(Vehicle):

def fare(self):
return super().fare() + self.capacity * 10

School_bus = Bus("School Volvo", 12, 100)


print(f"Total {School_bus.name} fare is:", School_bus.fare())

REPLY

Paul says
J A N U A R Y 2 1 , 2 0 2 1 AT 5 : 2 7 A M

In question 4, shouldn’t it be:


PYnative
Python Programming
 Learn Python  Exercises  Quizzes  Code Editor  Tricks
class Bus(Vehicle):
def seating_capacity(self, capacity=50):
return super().seating_capacity(capacity=capacity)

so that the capacity provided when, say, School_bus.seating_capacity(60) is called


would get passed to the super().seating_capacity()
REPLY

Mohit says
M AY 2 1 , 2 0 2 1 AT 1 2 : 1 9 P M

correct Paul ,

REPLY

Ryan says
D E C E M B E R 1 1 , 2 0 2 0 AT 1 1 : 4 9 P M

Exercise Question 6:

The help text states that outcome should be 5550.0 but the solution code and expected
output are both 5500.0.

REPLY

Vishal says
D E C E M B E R 1 2 , 2 0 2 0 AT 6 : 2 9 P M

Hey Ryan, Thank you for noticing the typing mistake. Now, I have fixed the typing
mistake.

REPLY

DMS KARUNARATNE says


S E P T E M B E R 1 7 , 2 0 2 0 AT 1 2 : 4 5 P M

Exercise Question 8: Determine if Bus is also an instance of the Vehicle class


need correction: Determine if School_bus is also an instance of the Vehicle class?

REPLY

Vishal says
S E P T E M B E R 1 7 , 2 0 2 0 AT 7 : 4 9 P M

Thank you for your correction.

REPLY

Leave a Reply
your email address will NOT be published. all comments are moderated according to our comment policy.

Comment *
PYnative
Python Programming
 Learn Python  Exercises  Quizzes  Code Editor  Tricks

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

Name * Email *

Post Comment

About PYnative Explore Python Follow Us Legal Stuff

PYnative.com is for Python lovers. Here, Learn Python To get New Python Tutorials, Exercises, About Us
You can get Tutorials, Exercises, and Python Basics and Quizzes Contact Us
Quizzes to practice and improve your
Python Databases Twitter We use cookies to improve your
Python skills.
Python Exercises experience. While using PYnative, you
Facebook
agree to have read and accepted our
Python Quizzes Sitemap
Terms Of Use, Cookie Policy, and
Online Python Code Editor
Privacy Policy.
Python Tricks

Copyright © 2018–2024 pynative.com

You might also like