Python Object-Oriented Programming Exercise - Classes and Objects Exercises

Posted in

Python Object-Oriented Programming Exercise - Classes and Objects Exercises
vinaykhatri

Vinay Khatri
Last updated on April 26, 2024

    Being an object-oriented programming language, Python supports OOP concepts - class, objects, inheritance, polymorphism, data encapsulation, and data abstraction. If you are a beginner learning Python, this object-oriented programming exercise will help you grasp OOP concepts quickly.

    The object-oriented programming paradigm works on objects that combine methods and properties. Its primary goal is to bring data and methods operating on that data together so that no other parts of the code can access that data.

    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 OOP 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

    Read: Python Object-Oriented Programming

    Let us get started with the Python OOP 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 use the class keyword, and to initialize the attribute during object creation, we 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

    #2. Write a Program to create a valid empty class with the name Students, with no properties.

    Solution:

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

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

    Refer topics

    #3. Write a program to create a child class Teacher that will inherit the properties from the parent class Staff.

    Solution:

    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

    #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}

    Refer Topics

    #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

    #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.

    Solution: 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

    #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

    #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 built-in 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

    #9. Write a Python program that lists all the default and custom properties of the class.

    Solution: 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.

    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']

    #10. Write a Python program 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 |

    #11. Write a program that prints the class name using its object.

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

    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

    #12. 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 in the comment box and let us know by posting your comment.

    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