Hackerrank Object-Oriented Programming Basics 2 — Questions and Answers
Question 1: Which method is automatically called when an object is created from a class?
- __init__ (Correct answer)
- __new__
- __create__
- __start__
Correct answer: __init__
__init__ is the initializer method called automatically after object creation to set up instance attributes.
Question 2: What does the 'self' parameter in an instance method refer to?
- The class itself
- The current instance of the class (Correct answer)
- The parent class
- A global variable
Correct answer: The current instance of the class
'self' refers to the current instance of the class, allowing access to instance attributes and methods.
Question 3: What will the following code output? class Dog: def __init__(self, name): self.name = name d = Dog('Rex') print(d.name)
- Dog
- Rex (Correct answer)
- self.name
- None
Correct answer: Rex
d.name accesses the instance attribute 'name' set during __init__, which was given the value 'Rex'.
Question 4: Which keyword is used to inherit from a parent class in Python?
- extends
- implements
- inherits
- The parent class is passed in parentheses (Correct answer)
Correct answer: The parent class is passed in parentheses
Python uses class ChildClass(ParentClass): syntax — the parent class name is placed in parentheses after the child class name.
Question 5: What is a class attribute vs an instance attribute?
- Class attributes are defined inside __init__; instance attributes are defined outside
- Class attributes are shared by all instances; instance attributes are unique per object (Correct answer)
- Class attributes are private; instance attributes are public
- There is no difference between them
Correct answer: Class attributes are shared by all instances; instance attributes are unique per object
Class attributes are defined at the class level and shared across all instances, while instance attributes are set per object via self.
Question 6: Which built-in function returns the class (type) of an object?
- isinstance()
- classof()
- type() (Correct answer)
- getclass()
Correct answer: type()
type(obj) returns the class of obj; e.g., type(42) returns <class 'int'>.
Question 7: What does 'encapsulation' mean in OOP?
- A class can inherit from multiple parent classes
- Data and methods are bundled together, with controlled access (Correct answer)
- A method can take any number of arguments
- Objects of a child class can replace parent class objects
Correct answer: Data and methods are bundled together, with controlled access
Encapsulation bundles data and the methods that operate on it inside a class, hiding internal details from outside code.
Which method is automatically called when an object is created from a class?