Learn Object-Oriented Programming in Python Educative Quiz Answers

Get Learn Object-Oriented Programming in Python Educative Quiz Answers

Learn to write cleaner, more modular, and more scaleable code in Python by gaining a master of Object Oriented Programming (OOP).

You’ll start with the basics of object oriented programming and build up to more advanced concepts such as inheritance, information hiding, and polymorphism. Along the way you’ll learn how each concept applies to Python in particular, as well as how various Python features make it particularly convenient for OOP.

This course is filled with hands-on coding challenges, playgrounds, snippets, and illustrations to keep things interactive.

Enroll on Educative

Quiz 1:

Q1. The containers for data and functions in a class definition can be divided into the following two types:

  • Methods and initalizers
  • Methods and access modifiers
  • Methods and properties
  • None of the above

Q2. What is the output of the code below?

class MyClass:
    def __init__(self, x, y):
        self.x = y
        self.y = x


obj1 = MyClass(2, 5)
print('x =', obj1.x)
print('y =', obj1.y)
  • x = 0
    y = 0
  • x= 2
    y= 5
  • x = 5
    y = 2
  • Runtime error

Q3. Methods and properties in Python class are public by default.

  • True
  • False

Q4. What will happen if we redefine a method several times and give it different arguments?

  • Python generates an error.
  • Python uses the latest method definition for its implementation
  • Python overloads the function.

Q5. If you don’t initialize properties in an initializer, the Python compiler will assign random values to them.

  • True
  • False

Challenge 1: Square Numbers and Return Their Sum

Answer:

class Point:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def sqSum(self):
        a = self.x * self.x
        b = self.y * self.y
        c = self.z * self.z
        return(a + b + c)

Challenge 2: Calculate the Student’s Performance

Answer:

class Student:
    def __init__(self, name, phy, chem, bio):
        self.name = name
        self.phy = phy
        self.chem = chem
        self.bio = bio

    def totalObtained(self):
        return(self.phy + self.chem + self.bio)

    def percentage(self):
        return((self.totalObtained() / 300) * 100)

Challenge 3: Implement a Calculator Class

Answer:

class Calculator:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

    def add(self):
        return (self.num2 + self.num1)

    def subtract(self):
        return (self.num2 - self.num1)

    def multiply(self):
        return (self.num2 * self.num1)

    def divide(self):
        return (self.num2 / self.num1)

Quiz 2:

Q1. What are the two components of data hiding?

  • Abstraction and Composition
  • Encapsulation and Abstraction
  • Encapsulation and Functions

Q2. As a rule of thumb, the data members of an encapsulated class should be declared ____________.

  • private
  • public

Q3. Data hiding makes sure that the implementation details are being hidden from the user.

  • True
  • False

Q4. To let a class communicate with the outside world, we implement ___________.

  • properties
  • methods
  • classes

Challenge 4: Implement Rectangle Class Using the Encapsulation

Answer:

class Rectangle:
    def __init__(self, length, width):
        self.__length = length
        self.__width = width

    def area(self):
        return (self.__length * self.__width)

    def perimeter(self):
        return (2 * (self.__length + self.__width))
    

Challenge 5: Implement the Complete Student Class

Answer:

class Student:
    def setName(self, name):
        self.__name = name

    def getName(self):
        return self.__name

    def setRollNumber(self, rollNumber):
        self.__rollNumber = rollNumber

    def getRollNumber(self):
        return self.__rollNumber
    

Exam 1:

Q1. Which of the following are basic entities in object-oriented programming?

  • Objects and methods
  • Objects and variables
  • Variables and classes
  • Objects and classes

Q2. The following code shows an incorrect way to create a class in Python. What is wrong with the syntax?

class MyClass {
  pass
}
  • The ‘class’ keyword should have been placed after ‘MyClass’
  • The curly braces should be replaced with a single colon after ‘MyClass’
  • The keyword ‘pass’ should be removed
  • We can’t create a class in Python that doesn’t have at least one attribute in it.

Q3. Will the code shown below throw an error? If yes, select why.

class Student:
    # defining the properties   
    ID = None
    GPA = None

# creating an object of the Student class
Peter = Student()

# assigning values to properties of Peter
Peter.ID = 3789
Peter.GPA = 3.5

# create a new attribute for Peter
Peter.department = "Computer Science"


# Create another Student object
John = Student()
John.ID = 3790
John.GPA = 3.7


# Printing properties of Peter
print("ID =", Peter.ID)
print("GPA", Peter.GPA)
print("Department:", Peter.department)

# Printing properties of John
print("ID =", John.ID)
print("GPA", John.GPA)
print("Department:", John.department)
  • It will throw an error because the new property ‘department’ can’t be assigned to an object of the Student class since it was never declared in the class definition.
  • It will throw an error because the new property ‘department’ was assigned to Peter and is not accessible to any other object of the Student class, therefore John can not access it.
  • It will throw an error because the properties of each object can not be accessed directly. We can only update or access these properties through defined class methods.
  • The code will execute without any error.

Q4. What is the correct syntax for an initializer method?

  • __initialize__()
  • __init__(self)
  • init()
  • initialize(self)

Q5. Which of the following statements explains how functions can be overloaded in Python?

  • We assign default values to those arguments in a method rather than creating a duplicate method with the same name.
  • We create different methods with the same name but a different number of arguments that are passed in each definition.

Q6. The code shown below will throw an error. Which of the given options will remove the error so the code executes properly?

class Student:
    def __init__(self, ID, GPA):
        self.ID = ID
        self.__GPA = GPA 

Steve = Student(3789, 3.6)
print("ID:", Steve.ID)
print("GPA:", Steve.__GPA)
  • The ‘ID’ attribute should be made private as well by changing it to ‘__ID’.
  • Add a method that returns the value in the ‘__GPA’ attribute and call that method instead of directly accessing the attribute itself.
  • The initializer method should have its arguments be assigned a ‘None’ value, allowing a learner to optionally assign custom values when initializing class objects.
  • Add a static method that returns the value in the ‘__GPA’ attribute. Use the static method to access the value stored in ‘__GPA’.

Q7. Given the following code, which option shows the correct format for accessing the private attribute, title, outside the class?

class Book:
    def __init__(self, ID, title):
        self.ID = ID
        self.__title = title


harry_potter = Book(3789, 'Harry Potter and the Chamber of Secrets')
print(harry_potter._Book__title) 
  • harry_potter._Book__title
  • harry_potter.Book.title
  • harry_potter.__title
  • harry_potter->title

Q8. Creating getter and setter methods in a class help propagate which important concept in object-oriented programming?

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Overloading

Q9. Which of the following is a valid point for Encapsulation?

  • All the properties should be public, and any access to the properties should be through directly accessing the attributes outside the class.
  • All the properties should be private, and any access to the properties should be through methods such as getters and setters which are also private.
  • All the properties should be private, and any access to the properties should be through methods such as getters and setters.
  • All the properties should be public, and any access to the properties should be through static methods.

Q10. Which syntax shows how the initializer method can be modified for a class to allow optional parameters?

  • __init__(self):
  • __init__(self, name = ””, ID = 0)
  • __init__(self, name, ID)

Q11. The column on the left contains different access types for attributes that belong to a class. The column on the right represents valid or invalid syntax for declaring and initializing variables in Python.

Match the access type in the left column with the correct variable declaration syntax in the right column.

  • private
    public
    static
  • x = 5
    __x = 5
    _~x = 5

Q12. A static method can be called by a class object.

  • True
  • False

Q13. You can add optional parameters to an initializer by assigning each parameter with ‘None’.

  • True
  • False

Q14. In this coding exercise, you are required to create a class Circle with a radius attribute.

The class should have a method print_area that calculates and prints the area of the circle.

For example, if a circle object with a radius of 33 is created:

obj = Circle(3)

Then, calling the function print_area should print the circle’s area, which in this case would be 28.2628.26

obj.print_area()

Note: You should also create an initializer method to assign the radius variable a value that can be assigned whenever a Circle class object is created.

Note: You can consider the value of pi to be 3.143.14.

Answer:

Q15. In this coding challenge, you will be required to create an encapsulated class Employee.

The Employee class will have the following private attributes:

  • name
  • ID
  • department

You will have to add getters and setters for each property.

The class will have the following methods:

  • get_name
  • set_name
  • get_ID
  • set_ID
  • get_department
  • set_department

Note: Make sure the attributes in the Employee class are private.

Answer:

Quiz 3:

Q1. Which of the following syntax is used to inherit ChildClass from the ParentClass?

  • Option 1
class ParentClass(ChildClass):
  • Option 2
class ChildClass(ParentClass):
  • Option 3
class ChildClass inherts ParentClass:
  • Option 4
class ChildClass extends ParentClass:

Q2. A child class can use all the __________ fields and methods of the parent class directly.

  • Private
  • Non-Private
  • Both

Q3.

class A:
    def __init__(self, x):
        self.x = x


class B(A):
    def __init__(self, x, y):
        self.y = y
        super().__init__(self, x)


b = B(5, 6)

The above code won’t compile because:

  • x is a private variable and cannot be accessed by the child class B.
  • When calling the parent initializer in the child initializer using super(), the self parameter is not used.
super().__init__(self,x)
  • should be the first line in the child initializer.

Q4. Which methods are called using the super keyword?

  • The current class methods
  • The parent class methods
  • Any method can be called
  • The child class methods

Q5. Calls to parent initializers using __init__( ) and super( ) can be written inside:

  • The methods only
  • The initializer only
  • Anywhere in a class

Challenge 6: Implement a Banking Account

Answer:

class Account:
    def __init__(self, title=None, balance=0):
        self.title = title
        self.balance = balance


class SavingsAccount(Account):
    def __init__(self, title=None, balance=0, interestRate=0):
        super().__init__(title, balance)
        self.interestRate = interestRate

Challenge 7: Handling a Bank Account

Answer:

class Account:  # parent class
    def __init__(self, title=None, balance=0):
        self.title = title
        self.balance = balance

    def withdrawal(self, amount):
        self.balance = self.balance - amount

    def deposit(self, amount):
        self.balance = self.balance + amount

    def getBalance(self):
        return self.balance


class SavingsAccount(Account):
    def __init__(self, title=None, balance=0, interestRate=0):
        super().__init__(title, balance)
        self.interestRate = interestRate

    def interestAmount(self):
        return (self.balance * self.interestRate / 100)


demo1 = SavingsAccount("Mark", 2000, 5)  # initializing a SavingsAccount object

Quiz 4:

Q1. What is the output of the following piece of code?

class Parent:
    def prn(self):
        print("Parent")


class Child(Parent):
    def __init__(self):
        self.a = Parent()

    def prn(self):
        print("Child")


temp = Child()
temp.a.prn()
  • Child
  • Child
    Parent
  • Parent
  • Compilation error

Q2. What is the output of the following piece of code?

class Parent:
    def prn(self):
        print("Parent")


class Child(Parent):
    def __init__(self):
        self.a = Parent()

    def prn(self):
        print("Child")


temp = Child()
temp.prn()
  • Child
  • Child
    Parent
  • Parent
  • None of the above

Q3. We can implement polymorphism using methods.

  • True
  • False

Q4. When overloading an operator, the second argument __________.

  • must be named other
  • can be named anything but the name other is used as per convention
  • must be named self

Q5. Methods with @abstractmethod decorators must be defined either in the parent class or the child class.

  • True
  • False

Challenge 8: Override a Method Using the Super Function

Answer:

class XShape(Shape):
    # initializer
    def __init__(self, name):
        self.xsname = name

    def getName(self):  # overriden method
        return (super().getName() + ", " + self.xsname)

Quiz 5:

Q1. In a part-of relationship between two classes ____________.

  • Both classes must be a part of the other.
  • One class object must be a part of the other.
  • Both classes should be parts of a third class.

Q2. What kind of relationship does composition use?

  • Part-of
  • Has-A
  • None of the above

Q3. ____________ is when an object has its own lifecycle and a child object cannot belong to another owner object.

  • Association
  • Composition
  • Aggregation
  • Inheritance

Q4. Two associated classes cannot exist independently.

  • True
  • False

Q5. Association is the most basic way to relate classes without inheritance.

  • True
  • False

Exam 2: OOP in Python

Q1. What will be the output of the following code?

class Music:  # defining the parent class
    total_songs = 100


class Rock(Music):  # defining the child class
    total_songs = 30

    def display(self):
        print(self.total_songs)

        print(super().total_songs)


genre = Rock()  
genre.display()
  • 100 30
  • 30 100
  • 130
  • runtime error

Q2. What type of inheritance does the following scenario best embody?

The class Department is a parent class that is inherited by the child classes ComputerScience and Mathematics.

class Department:  # parent class
    
    def __init__(self, title):
        self.title = title

class ComputerScience(Department):  # child class 
    pass

class Mathematics(Department):  # child class
    pass
  • Multi-level inheritance
  • Hierarchical inheritance
  • Single inheritance
  • multiple inheritance

Q3. Which option is an example of the hybrid inheritance type?

  • “The Lord of the Rings” is a movie and a book.
  • A car is a vehicle.
  • An elephant is a mammal. A mammal is an animal.
  • Horror and action are both different genres.

Q4. Which of the given options is not an advantage of implementing inheritance?

  • Re-usability
  • Data Hiding
  • Extensibility
  • Code redundancy

Q5. What is the output of the following code?

class Vehicle:

    def displayType(self):
        print("This is a vehicle")
 
 
class Car(Vehicle):
 
    def displayType(self):
        print("This is a car")

class Bus(Vehicle):
    
    def displayType(self):
        print("This is a bus")
 
 
c = Car()
b = Bus()
v = Vehicle()

c.displayType()
b.displayType()
v.displayType()
  • This is a car This is a bus This is a vehicle
  • This is a bus This is a car This is a vehicle
  • This is a vehicle This is a bus This is a car
  • The code will give a runtime error.

Q6. What will be the output of the code given below?

class A:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __add__(self, num):
        return A((self.x + num.x) * 2)

    def __sub__(self, num):  
        return A((self.x - num.x) * 2)


obj1 = A(3)
obj2 = A(5)

obj3 = obj1 + obj2
obj4 = obj1 - obj2

print("obj.x = ", obj3.x)
print("obj3.y = :", obj3.y)
print("obj4.x = :", obj4.x)
print("obj4.y = ", obj4.y)
  • obj3.x = 9 obj4.x = : -4
  • obj3.x = 0 obj4.x = : 4
  • obj3.x = 8 obj4.x = : 2
  • obj3.x = 16 obj4.x = : -4

Q7. Which option defines aggregation and composition accurately?

  • In aggregation, the lifetime of the owned object does not depend on the lifetime of the owner. In composition, the lifetime of the owned object depends on the lifetime of the owner.
  • In aggregation, the lifetime of the owned object depends on the lifetime of the owner. In composition, the lifetime of the owned object does not depend on the lifetime of the owner.
  • In aggregation, the lifetime of the owned object defines the lifetime of the owner. In composition, the lifetime of the owned object depends on the lifetime of the owner.
  • In aggregation, the lifetime of the owned object does not depend on the lifetime of the owner. In composition, the lifetime of the owned object also does not depend on the lifetime of the owner.

Q8. What will be the output of each print statement in the code?

x = 5 
print(type(x)) #statement 1

x = 5.6
print(type(x)) #statement 2

x = 'hello'
print(type(x)) #statement 3
  • statement 1
    statement 2
    statement 3

Q9. A child class can access all public attributes and methods of the parent class.

  • true
  • False

Q10. The given code execute without throwing an error.

class Vehicle:
    def __init__(self, name):
        self.name = name
 
 
class Car(Vehicle):
    def __init__(self, name):
        super().__init__(self, name)
 
 
obj = Car('Tesla')
  • True
  • False

Q11. The given code is an example of aggregation.

class Ingredient:
    def __init__(self, name=''):
        self.name = name

    def printDetails(self):
        print(self.name)


class Pizza:
    def __init__(self, cheese, tomato, topping, dough):
        self.cheese = Ingredient(cheese)
        self.tomato = Ingredient(tomatato)
        self.pepperoni = Ingredient(topping)
    
    def __init__(self, name='', quantitiy=0):
        self.name = name

    def printDetails(self):
        print(self.name)


class Pizza:
    def __init__(self, cheese, tomato, topping, dough):
        self.cheese = Ingredient(cheese)
        self.tomato = Ingredient(tomato)
        self.topping = Ingredient(topping)
        self.dough = Ingredient(dough)


    def printIngredients(self):
        self.cheese.printDetails()
        self.tomato.printDetails()
        self.topping.printDetails()
        self.dough.printDetails()

pepperoni_pizza = Pizza('cheese', 'tomato', 'pepperoni', 'dough')
pepperoni_pizza.printIngredients()
  • True
  • False

Q12. The given code compiles properly.

from abc import ABC, abstractmethod


class Shape(ABC):  # Shape is a child class of ABC
    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass


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

    def area(self):
        return (self.length * self.length)

    def perimeter(self):
        return (4 * self.length)


shape = Shape()
  • True
  • False

Q13. This coding challenge will test your concepts on inheritance and polymorphism. You are asked to create a class Country that will contain a name attribute.

You will be provided with base classes that inherit from the Country class. You will need to add a method to the derived classes called print_continent that will state which continent that country belongs to.

For example, given an object of the class India:

obj = India()

The print_continent method should give the following output:

Asia

Similarly, given an object of the France class:

obj = France()

The print_continent method should give the following output:

Europe

Answer:

Q14. For this coding challenge, you are asked to create an Employee and a Salary class. The Employee class will have the following attributes:

  • name
  • salary

The Salary class will have the following attributes:

  • base_salary
  • bonus

For this use case, the Employee class object will compose a Salary class object as well.

Note: Some helper methods have already been added to the classes, which you can use for your solution.

You will need to create the following methods for each class:

EmployeeSalary
get_nameget_bonus
set_nameset_bonus
get_salaryget_base_pay
set_salaryset_base_pay

Note: The get_salary method should return a sum of the bonus and base_pay values.

Note: The set_salary method should have two input parameters, base_pay and bonus.

Answer:

Q15. For this coding challenge, you are expected to create an abstract base class. The base class will be called Metal, and it will have three child classes, AluminumCopper, and Gold.

All of the derived classes will have a method — called get_melting_point — that will be inherited from the base class.

The get_melting_point method will return the temperature in Degree Celsius. The table below provides the melting points of the metals:

MetalMelting Point
Aluminum660^{\circ} C660∘C
Copper1084^{\circ} C1084∘C
Gold1063^{\circ} C1063∘C

Note: The melting point of a metal is always the same and won’t change. Therefore, you can choose to keep the value as a constant.

Answer:

Conclusion:

I hope this Learn Object-Oriented Programming in Python Educative Quiz Answers would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.