Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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.
Q1. The containers for data and functions in a class definition can be divided into the following two types:
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)
Q3. Methods and properties in Python class are public by default.
Q4. What will happen if we redefine a method several times and give it different arguments?
Q5. If you don’t initialize properties in an initializer, the Python compiler will assign random values to them.
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)
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)
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)
Q1. What are the two components of data hiding?
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.
Q4. To let a class communicate with the outside world, we implement ___________.
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))
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
Q1. Which of the following are basic entities in object-oriented programming?
Q2. The following code shows an incorrect way to create a class in Python. What is wrong with the syntax?
class MyClass {
pass
}
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)
Q4. What is the correct syntax for an initializer method?
Q5. Which of the following statements explains how functions can be overloaded in Python?
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)
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)
Q8. Creating getter and setter methods in a class help propagate which important concept in object-oriented programming?
Q9. Which of the following is a valid point for Encapsulation?
Q10. Which syntax shows how the initializer method can be modified for a class to allow optional parameters?
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.
Q12. A static method can be called by a class object.
Q13. You can add optional parameters to an initializer by assigning each parameter with ‘None’.
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 aCircle
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:
Q1. Which of the following syntax is used to inherit ChildClass
from the ParentClass
?
class ParentClass(ChildClass):
class ChildClass(ParentClass):
class ChildClass inherts ParentClass:
class ChildClass extends ParentClass:
Q2. A child class can use all the __________ fields and methods of the parent class directly.
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
.super()
, the self
parameter is not used.super().__init__(self,x)
Q4. Which methods are called using the super
keyword?
Q5. Calls to parent initializers using __init__( )
and super( )
can be written inside:
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
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
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()
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()
Q3. We can implement polymorphism using methods.
Q4. When overloading an operator, the second argument __________.
other
other
is used as per conventionself
Q5. Methods with @abstractmethod
decorators must be defined either in the parent class or the child class.
Answer:
class XShape(Shape):
# initializer
def __init__(self, name):
self.xsname = name
def getName(self): # overriden method
return (super().getName() + ", " + self.xsname)
Q1. In a part-of relationship between two classes ____________.
Q2. What kind of relationship does composition use?
Q3. ____________ is when an object has its own lifecycle and a child object cannot belong to another owner object.
Q4. Two associated classes cannot exist independently.
Q5. Association is the most basic way to relate classes without inheritance.
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()
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
Q3. Which option is an example of the hybrid inheritance type?
Q4. Which of the given options is not an advantage of implementing inheritance?
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()
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)
Q7. Which option defines aggregation and composition accurately?
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
Q9. A child class can access all public attributes and methods of the parent class.
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')
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()
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()
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:
Employee | Salary |
---|---|
get_name | get_bonus |
set_name | set_bonus |
get_salary | get_base_pay |
set_salary | set_base_pay |
Note: The
get_salary
method should return a sum of thebonus
andbase_pay
values.
Note: The
set_salary
method should have two input parameters,base_pay
andbonus
.
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, Aluminum
, Copper
, 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:
Metal | Melting Point |
---|---|
Aluminum | 660^{\circ} C660∘C |
Copper | 1084^{\circ} C1084∘C |
Gold | 1063^{\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:
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 >>