PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises

Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises

Updated on: April 17, 2025 | 56 Comments

This Object-Oriented Programming (OOP) exercise aims to help you to learn and practice OOP concepts. All questions are tested on Python 3.

Python Object-oriented programming (OOP) is based on the concept of “objects,” which can contain data and code: data in the form of instance variables (often known as attributes or properties), and code, in the form method. I.e., Using OOP, we encapsulate related properties and behaviors into individual objects.

What is included in this Python OOP exercise?

This OOP classes and objects exercise includes 10 coding questions, programs, and challenges. All solutions are tested on Python 3.

This exercise covers questions on the following topics:

  • Class and Object creation
  • Instance variables and Methods, and Class level attributes
  • Model systems with class inheritance i.e., inherit From Other Classes
  • Parent Classes and Child Classes
  • Extend the functionality of Parent Classes using Child class
  • Object checking

When you complete each question, you will become more familiar with Object-Oriented Programming. Please let us know if you have any alternative solutions; it will help other developers.

Use Online Code Editor to solve exercise questions.

Refer:

  • Guide on Python OOP
  • Inheritance in Python
  • Python OOP Interview Questions

Table of contents

  • OOP Exercise 1: Create a Class with instance attributes
  • 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
  • OOP Exercise 5: Define a property that must have the same value for every class instance (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 9: Check object is a subclass of a particular class
  • OOP Exercise 10: Calculate the area of different shapes using OOP

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
  • Constructors 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)Code language: Python (python)

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

Show Solution
class Vehicle:
    passCode language: Python (python)

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 = mileageCode language: Python (python)

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:", School_bus.mileage)Code language: Python (python)

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"Code language: Python (python)

Expected Output:

The seating capacity of a bus is 50 passengers

Refer:

  • Inheritance in Python
  • 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())Code language: Python (python)

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):
    passCode language: Python (python)

Expected Output:

Color: White, Vehicle name: School Volvo, Speed: 180, Mileage: 12
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 values of the name and max_speed variables will vary depending on the Vehicle instance.

On the other hand, a 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:", School_bus.mileage)

car = Car("Audi Q5", 240, 18)
print(car.color, car.name, "Speed:", car.max_speed, "Mileage:", car.mileage)Code language: Python (python)

OOP Exercise 6: Class Inheritance

Given:

Create a Bus child class that inherits from the Vehicle class. The default fare charge for any vehicle is its seating capacity multiplied by 100 (seating capacity * 100).

If the vehicle is a Bus instance, we need to add an extra 10% to the full fare as a maintenance charge. Therefore, the total fare for a Bus instance will be the final amount, calculated as total fare plus 10% of the total fare. (final amount = total fare + 10% of the total fare.)

Note: The bus seating capacity is 50, so the final fare amount should be 5500.

Use the following code for your parent Vehicle class. We need to access the parent class from within 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())Code language: Python (python)

Expected Output:

Total Bus fare is: 5500.0
Show Hint
  • You need to override the fare() method of the Vehicle class in the Bus class.
  • Use super() function within a child class to call methods of a parent (or super) class.

Method overriding lets a subclass provide its own version of a method that its superclass already has. It allows the subclass to customize or specialize the behavior inherited from the superclass.

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())Code language: Python (python)

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
        self.capacity = capacity

class Bus(Vehicle):
    pass

School_bus = Bus("School Volvo", 12, 50)Code language: Python (python)
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))Code language: Python (python)

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)Code language: Python (python)
Show Hint

Use isinstance() function

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 isinstance() function
print(isinstance(School_bus, Vehicle))Code language: Python (python)

OOP Exercise 9: Check object is a subclass of a particular class

Given:

class Animal:
    pass

class Dog(Animal):
    pass

class Puppy(Dog):
    pass

class Cat:
    passCode language: Python (python)

Write a code to check the following

  1. Dog is a subclass of Animal? –> True
  2. Animal is a subclass of Dog? –> False
  3. Cat is a subclass of Animal? –> False
  4. Puppy is a subclass of Animal –> True
Show Hint

Use the issubclass() function. The issubclass(potential_subclass, potential_superclass) returns True if the first argument is a subclass (or the same class) of the second argument, and False otherwise.

Show Solution
class Animal:
    pass

class Dog(Animal):
    pass

class Puppy(Dog):
    pass

class Cat:
    pass

print(issubclass(Dog, Animal))   # Output: True  (Dog is a subclass of Animal)
print(issubclass(Animal, Dog))   # Output: False (Animal is not a subclass of Dog)
print(issubclass(Cat, Animal))    # Output: False (Cat is not related to Animal)
print(issubclass(Puppy, Animal)) # Output: True (Puppy inherits from Dog, which inherits from Animal)Code language: Python (python)

OOP Exercise 10: Calculate the area of different shapes using OOP

Given:

You have given a Shape class and subclasses Circle  and Square. The parent class (Shape) has a area() method.

Now, Write a OOP code to calculate the area of each shapes (each subclass must write its own implementation of area() method to calculates its area).

Use the following code

class Shape:
    def area(self):
        raise NotImplementedError("Area method must be implemented by subclasses")

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

class Square(Shape):
    def __init__(self, side):
        self.side = side

# Example of polymorphism
shapes = [Circle(5), Square(7), Circle(3)]

for shape in shapes:
    print(shape.area())  # Output: 78.53975, 49, 28.27431Code language: Python (python)

Refer:

  • Inheritance in Python
  • Polymorphism in Python
Show Hint
  • Use Method Overloading.
  • The core idea is that the same method name can have different implementations depending on the class of the object.

Polymorphism lets you treat objects of different classes in a uniform way. Imagine you have a Shape class, and then you have subclasses like Circle, Square, and Triangle. Each of these shapes has an area() method, but the way you calculate the area is different for each shape.

Show Solution
class Shape:
    def area(self):
        raise NotImplementedError("Area method must be implemented by subclasses")

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):  # Overriding the area method
        return 3.14159 * self.radius**2

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):  # Overriding the area method
        return self.side * self.side

# Example of polymorphism
shapes = [Circle(5), Square(7), Circle(3)]

for shape in shapes:
    print(shape.area())  # Output: 78.53975, 49, 28.27431Code language: Python (python)

Also, See: Python OOP Interview Questions

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.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Exercises Python Object-Oriented Programming (OOP)

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

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

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. ImageAisha says

    December 4, 2025 at 5:49 pm

    Thank you for putting this together and sharing. It’s a really helpful practice/revision exercise, and I learnt new things.

    Reply
    • ImageVishal says

      January 22, 2026 at 3:54 pm

      Thank you!

      Reply
  2. Imageotwjunior says

    June 19, 2025 at 1:26 pm

    thanks man for the assistance you make me understand oop

    Reply
  3. ImageDan says

    August 15, 2024 at 4:33 pm

    Moving way too fast. By the time i got to 5, i forgot how to do 1.

    Reply
  4. ImageAlija Rai says

    May 6, 2024 at 1:25 pm

    Thank you Vishal sir, for providing the exercises, As a beginner these exercises have helped us a lot.

    Reply
  5. ImageKavindu says

    August 19, 2023 at 3:45 pm

    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

    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
  6. ImageDriss Fadal says

    August 2, 2023 at 4:14 am

    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
  7. ImageMokhtar Mahmoudian says

    March 4, 2023 at 12:06 am

    #Exercise 3
    class Vehicle:
    def __init__(self ,Max_speed, Mileage):
    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
  8. ImageAdrian says

    February 28, 2023 at 10:10 pm

    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
    • ImageReef says

      October 11, 2023 at 1:47 am

      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
  9. ImageDealer says

    January 20, 2023 at 7:28 pm

    Exercise 7, is this a good practice?

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

    class Bus(Vehicle):
    @staticmethod
    def which_class():
    return __class__.__name__

    School_bus = Bus("School Volvo", 12, 50)
    print(School_bus.which_class())

    Reply
    • Imageayoub says

      January 22, 2023 at 11:21 pm

      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
      • ImageUtkarsh Dadaso Salunkhe says

        February 23, 2023 at 9:55 pm

        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.”)

        Reply
  10. ImageDealer says

    January 20, 2023 at 6:58 pm

    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
  11. ImageLUQMAN HAQIM says

    November 13, 2022 at 9:24 pm

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

    class vehicle:

    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
    • ImageKaran says

      January 6, 2023 at 12:18 pm

      class vehicle:
      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(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
  12. ImageAnkit Shukla says

    September 20, 2022 at 12:37 pm

    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 maintenance charge
            total_fare = fare + (fare*0.10)
            return total_fare
            
    
    School_bus = Bus("School Volvo", 12)
    print("Total Bus fare is:", School_bus.fare())
    Reply
  13. ImageAnkit Shukla says

    September 20, 2022 at 12:35 pm

    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 maintenance charge
            total_fare = fare + (fare*0.10)
            return total_fare
            
    
    School_bus = Bus("School Volvo", 12)
    print("Total Bus fare is:", School_bus.fare())
    Reply
    • ImageSherrif says

      December 4, 2022 at 4:36 pm

      This is good approach, clean code, good practice.

      Reply
  14. ImageSunny says

    July 28, 2022 at 5:14 pm

    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):
            print("The fare for {} is {}".format(self.name, int(self.capacity)*100))
        
        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 + int((int(self.capacity)*100)//10)))
    
    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
  15. ImageFabrizio says

    July 7, 2022 at 5:45 pm

    An alternative way of doing exercise 6:

    
    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
  16. ImageLawrence says

    July 1, 2022 at 12:09 pm

    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
    • Imageavi says

      July 6, 2022 at 7:13 pm

      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 the 10%
      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
  17. ImageHanna Damarjian says

    June 29, 2022 at 1:10 am

    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
    • ImagePrashant says

      January 6, 2025 at 6:40 am

      “return super().fare() + 0.10*super().fare()”, this will call parent method twice, so better we can do with this way..

      def fare(self):
      orgfare = super().fare()
      return (orgfare + orgfare * 0.1)

      Reply
  18. ImageCyrus says

    May 12, 2022 at 12:33 am

    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
    • ImageSuraj says

      May 20, 2022 at 8:35 pm

      Call the function as print(bus.seating_capacity(50))
      output:
      The seating capacity of a bus is 50 passengers

      NO problem!

      Reply
  19. ImageMasha says

    April 23, 2022 at 1:10 pm

    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
  20. Imageabc says

    April 20, 2022 at 8:32 am

    Thanks a ton for the well-curated structure.

    Reply
  21. ImageDaniel says

    March 17, 2022 at 5:14 pm

    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):
            return self.capacity * 110
    
    School_bus = Bus("School Volvo", 12, 50)
    print("Total Bus fare is:", School_bus.fare())
    Reply
    • ImageGanymehdi says

      April 13, 2022 at 1:06 am

      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
      • ImageCyrus says

        May 13, 2022 at 12:52 am

        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
  22. ImageNagimesi Khatwiibu Shuaibu says

    March 3, 2022 at 9:54 pm

    very good codes

    Reply
  23. ImageRaji says

    March 1, 2022 at 5:08 pm

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

    Reply
  24. ImageSuraj Thapa says

    January 31, 2022 at 5:02 am

    Thank you very much.

    Reply
  25. ImageJitendra chandra says

    December 29, 2021 at 8:39 am

    Thanks a lot Brother !

    Reply
  26. ImageLilit Grigoryan says

    November 11, 2021 at 3:16 pm

    Thank’s a lot, I enjoyed the tasks.

    Reply
    • ImageVishal says

      November 14, 2021 at 11:09 am

      You’re welcome, Lilit.

      Reply
      • ImageSaikiran Tangudu says

        December 30, 2021 at 11:28 am

        HI Vishal please post more questions on oops

        Reply
  27. ImageknotJ says

    October 18, 2021 at 8:14 pm

    Thanks. learnt lots

    Reply
  28. ImageJokunsoo says

    July 9, 2021 at 5:28 pm

    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)
    Transit_bus = Vehicle("Tesla van", 12000, 2)
    
    Transit_bus.qclass()
    Reply
  29. ImageAbhay Kumar Mishra says

    May 19, 2021 at 4:02 pm

    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: {self.mileage}'
    
    
    school_bus = Bus('Volvo',180,12)
    print(school_bus.bus_info())
    Reply
  30. ImageMr. Lulz says

    April 26, 2021 at 4:22 am

    This was a fun exercise!

    Reply
  31. Imagevish says

    April 19, 2021 at 3:11 pm

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

    Thanks for support…

    Reply
  32. Imagedhruv says

    April 14, 2021 at 6:14 pm

    thank you vishal sir it’s very help me

    Reply
    • ImageVishal says

      April 16, 2021 at 7:54 pm

      I am glad it helped you, Dhruv.

      Reply
  33. ImageEtra Arte says

    March 19, 2021 at 12:13 am

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

    Reply
    • ImageVishal says

      March 21, 2021 at 11:25 am

      I am glad it helped you.

      Reply
  34. ImageEmmanuel Bett says

    February 15, 2021 at 11:17 pm

    thank you…Awesome learning experience

    Reply
  35. ImageLamhamdi says

    January 31, 2021 at 11:04 pm

    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
  36. ImagePaul says

    January 21, 2021 at 5:27 am

    In question 4, shouldn’t it be:

    
    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
    • ImageMohit says

      May 21, 2021 at 12:19 pm

      correct Paul ,

      Reply
  37. ImageRyan says

    December 11, 2020 at 11:49 pm

    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
    • ImageVishal says

      December 12, 2020 at 6:29 pm

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

      Reply
  38. ImageDMS KARUNARATNE says

    September 17, 2020 at 12:45 pm

    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
    • ImageVishal says

      September 17, 2020 at 7:49 pm

      Thank you for your correction.

      Reply

Leave a Reply Cancel reply

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

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

In: Python Python Exercises Python Object-Oriented Programming (OOP)
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement