Python Object-Oriented Programming Exercise - Classes and Objects Exercises

Posted in /  

Python Object-Oriented Programming Exercise - Classes and Objects Exercises

Vinay Khatri
Last updated on September 29, 2022

    Python is an Object-Oriented Programming language, which means it supports the concept of OOPs such as class, objects, inheritance, polymorphism, data encapsulation, and data abstraction. The class and object concepts come under basic Python programming. After learning functions and operators, every Python learner learns Object-oriented programming.

    Like other programming concepts, the best thing after learning any syntax is practicing the concept exercises and improving the skills. The same goes for Python object-oriented programming. In this Python Object Oriented Programming exercise, we will solve some of the common OOPs problem statements that include the following topics.

    1. Python class and objects
    2. Python class properties, methods, and attributes.
    3. Python class private and global properties
    4. Python class inheritance.
    5. Python Polymorphism
    6. Python object checking

    By the end of this Python exercise, you will become more familiar with Python OOPs concepts.

    Python OOPs Exercise 1: Write a Program to create a class by name Students, and initialize attributes like name, age, and grade while creating an object.

    Solution: To create a class in Python, we can use the class, and to initialize the attribute during object creation, we can define the __init__() method.

    class Students:
        #initialize the properties
        def __init__(self, name, age, grade):
            self.name = name
            self.age = age
            self.grade = grade
    
    #create object
    raj = Students('Raj', 16, '11th')

    Refer topics

    Python OOPs Exercise 2: Write a Program to create a valid empty class by name Students, with no properties

    class Students:
        pass
    
    #create object
    raj = Students()

    The pass keyword allows us to leave a block code without any body definition. Refer topics

    Python OOPs Exercise 3: Write a program to create a child class Teacher that will inherit the properties of Parent class Staff

    class Staff:
        def __init__(self, role, dept, salary): 
            self.role = role
            self.dept = dept
            self.salary = salary
    
        def show_details(self):
            print("Name: ", self.name)
            print("Age: ", self.age)
            print("Role:", self.role)
            print("Department:", self.dept)
    
    #inherit from the Staff class
    class Teacher(Staff):
        def __init__(self, name, age):
            self.name = name
            self.age = age
            # initialize the Parent  class
            super().__init__("Teacher", "Science", 25000)
    
    
    teacher = Teacher("Raj", 28)
    
    #access the Staff Method
    teacher.show_details()

    Output

    Name:  Raj
    Age:  28
    Role: Teacher
    Department: Science

    Refer Topics

    Python OOPs Exercise 4: Write a Program to create a class and, using the class instance, print all the writable attributes of that object.

    Solution Every class object has an inbuilt __dict__ attribute that returns a dictionary of all the attributes available for that object.

    class Staff:
        def __init__(self, role, dept, salary): 
            self.role = role
            self.dept = dept
            self.salary = salary
    
        def show_details(self):
            print("Name: ", self.name)
            print("Age: ", self.age)
            print("Role:", self.role)
            print("Department", self.dept)
    
    #inherit from the Staff class
    class Teacher(Staff):
        def __init__(self, name, age):
            self.name = name
            self.age = age
            # initialize the Parent  class
            super().__init__("Teacher", "Science", 25000)
    
    teacher = Teacher("Raj", 45)
    
    #display all the namespaces
    print(teacher.__dict__)

    Output

    {'name': 'Raj', 'age': 45, 'role': 'Teacher', 'dept': 'Science', 'salary': 25000}

    Python OOPs Exercise 5: What would be the output of the following program?

    class Staff:
        def __init__(self, role, dept, salary): 
            self.role = role
            self.dept = dept
            self.salary = salary
    
        def show_details(self):
            print("Name: ", self.name)
            print("Age: ", self.age)
            print("Role:", self.role)
            print("Department", self.dept)
    
    #inherit from the Staff class
    class Teacher(Staff):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
            # initialize the Parent  class
            super().__init__("Teacher", "Science", 25000)
    
    teacher = Teacher("Raj", 45)
    
    print(isinstance(teacher, Teacher))
    
    print(isinstance(teacher,Staff))

    Output

    True
    True

    Python OOPs Exercise 6: Create a class Teacher with name, age, and salary attributes, where salary must be a private attribute that cannot be accessed outside the class.

    Answer In Python, there is no such thing as Private attributes or private members. Still, we can follow the convention of putting double underscore __ before the variable name to make it private. Even after putting the double underscore before an attribute, it can still be accessed using the following syntax _Classname__attributeName .

    class Teacher():
        def __init__(self, name, age, salary):
            self.name = name
            self.age = age
    
            # private variable
            self.__salary = salary
    
        def show_details(self):
            print("Name:", self.name)
            print("Age:", self.age)
    
            #access private attribute inside the class
            print("Salary: ", self.__salary)
    
    teacher = Teacher("Raj", 45, 25000)
    
    teacher.show_details()
    
    # print(teacher.name)   #Raj
    
    #access private member outside the class will throw error
    # print(teacher.__salary)   #error

    Output

    Name: Raj
    Age: 45
    Salary:  25000

    Python OOPs Exercise 7: Write a Python program that overloads the operator + and > for a custom class.

    Solution: Python custom class support operator overloading. To overload the operators for the class objects, we define the specific dunders method. For the + operator the dunder method is __add__() and for > its __gt__()

    class Orders:
        def __init__(self, items):
            self.items = items
    
        # overload the + operator
        def __add__(self, other):
            return self.items + other.items
    
        # overload the > operator
        def __gt__(self, other):
            return len(self.items) > len(other.items)
    
    order1 = Orders([1, 2, 3, 4, 5, 6])
    
    order2 = Orders([10, 20, 30])
    
    print("order1 + order2=", order1 + order2)
    print("order1 > order2=", order1 > order2)

    Output

    order1 + order2= [1, 2, 3, 4, 5, 6, 10, 20, 30]
    order1 > order2= True

    Python OOPs Exercise 8: Write a Python program that checks if one class is a subclass of another.

    Solution: To check if a class is a subclass of another, we can use the Python inbuilt the issubclass() function.

    class Staff:
        def show_details(self):
            print("Name: ", self.name)
            print("Age: ", self.age)
    
    # inherit from the Staff class
    class Teacher(Staff):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    print("Is Teacher a subclass of Staff:", issubclass(Teacher, Staff))
    print("Is Staff a subclass of Teacher:", issubclass(Staff, Teacher))

    Output

    Is Teacher a subclass of Staff: True
    Is Staff a subclass of Teacher: False

    Python OOPs Exercise 9: Write a Python program that lists out all the default as well as custom properties of the class.

    Answer: All the properties of a class can be accessed through its object. By using the python dir() function on a class object, we can list out all the methods and attributes of the object or class. Example

    class Teacher:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    teacher = Teacher("Lokesh", 36)
    print("Teacher class's object  all properties")
    
    print(dir(teacher))

    Output

    ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
     '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', 
    '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
    '__sizeof__', '__str__', '__subclasshook__', 
    '__weakref__', 'age', 'name']

    Python OOPs Exercise 10: Write a Program in Python to implement a Stack Data Structure using Class and Objects, with push, pop, and traversal methods.

    Solution:

    class Stack:
        # initialize an empty list
        def __init__(self):
            # conventional private member
            self.__stack = []
    
        # add items to the stack
        def push(self, item):
            self.__stack.append(item)
    
        # pop item from the stack
        def pop(self):
            self.__stack.pop()
    
        def traverse(self):
            for item in self.__stack[::-1]:
                print("|", item, "|")
    
    # initialize the object
    stack = Stack()
    
    # push item to the stack
    stack.push(1)
    stack.push(2)
    stack.push(3)
    stack.push(4)
    stack.push(5)
    stack.push(6)
    stack.push(7)
    stack.push(8)
    stack.push(9)
    
    # pop items from the stack
    stack.pop()
    stack.pop()
    
    # traverse through the stack
    stack.traverse()

    Output

    | 7 |
    | 6 |
    | 5 |
    | 4 |
    | 3 |
    | 2 |
    | 1 |

    Python OOPs Exercise 11: Write a program that prints the class name using its object.

    Solution. Using the object’s __class__.__name__ property, we can access the class Name of the object.

    class Animal:
        pass
    
    
    # Animal class object
    lion = Animal()
    
    print("The ClassName of the lion object is: ", lion.__class__.__name__)

    Output

    The ClassName of the lion object is:  Animal

    Python OOPs Exercise 11: Write a Python class Square, and define two methods that return the square area and perimeter.

    Solution:

    class Square:
        def __init__(self, side):
            self.side = side
    
        def area(self):
            return self.side * self.side
    
        def perimeter(self):
            return 4*(self.side)
    
    #initialize the objects of Square class
    square1 = Square(10)
    square2 = Square(20)
    
    print("The Area of square1 is:", square1.area())
    print("The Perimeter of square1 is:", square1.perimeter())
    
    print("\n\nThe Area of square2 is:", square2.area())
    print("The Perimeter of square2 is:", square2.perimeter())

    Output

    The Area of square1 is: 100
    The Perimeter of square1 is: 40
    
    
    The Area of square2 is: 400
    The Perimeter of square2 is: 80

    Conclusion

    Object-Oriented Programming is the most important part of Python because Python is implemented using the OOP’s concept and everything in Python is an object. From primitive data type int to complex functions, everything is just an object that has defined classes.

    In this Python tutorial, we discussed some of the basic Python object-oriented programming exercises with solutions. It’s just a starter exercise that you can practice after learning the basic Python OOPs. With the help of class and objects, you can implement complex algorithms in Python that cannot be implemented using just a Procedural Programming Structure.

    If you like this Python OOPs exercise or want to add more problem statements, please fill the comment box and let us know by posting your comment.

    To have a better understanding of OOPs with Python, purchase the course here.

    People are also reading:

    FAQs


    Initially, learn object-oriented concepts, like classes, objects, abstraction, inheritance, polymorphism, and encapsulation. Later, you can refer to the above set of Python object-oriented problems with solutions to practice the learned concepts.

    Yes, you can learn Python for free. There are numerous tutorials available on the internet. Also, many e-learning platforms, including Udemy, edX, Coursera, and LinkedIn Learning, offer free Python introductory courses where you can learn Python basics.

    After you learn Python concepts, it is necessary to put them into practice to have a better grasp of them. There are websites that let you put Python concepts into practice by solving problems. They include Coderbyte, Geektastic, freeCodeCamp, HackerRank, HackerEarth, TopCoder, and CodinGame.

    Leave a Comment on this Post

    0 Comments