Python Programming - Objects
Exercise : Objects - General Questions
- Objects - General Questions
6.
Consider the following Python code:
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius * self.radius
How would you create an instance of the Circle class with a radius of 5?
Answer: Option
Explanation:
The correct way to create an instance of the Circle class with a radius of 5 is to use the constructor and pass the value as a named argument.
7.
Which method is automatically called when an object is created?
Answer: Option
Explanation:
The
__init__
method is automatically called when an object is created in Python, allowing you to initialize the object's attributes.
8.
Consider the following Python code:
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return True
else:
return False
What does the withdraw
method return if the withdrawal is successful?
Answer: Option
Explanation:
The
withdraw
method returns True
if the withdrawal is successful, indicating that the amount was deducted from the balance.
9.
In Python, what is the purpose of the
__str__
method in a class?
Answer: Option
Explanation:
The
__str__
method is used to define a human-readable string representation of the object when the str()
function is called.
10.
Consider the following Python code:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def birthday(self):
self.age += 1
If you create an instance of the Student class called john
with age 20 and then call john.birthday()
, what will be the updated age?
Answer: Option
Explanation:
The
birthday
method increments the age attribute by 1, so after calling john.birthday()
, the updated age will be 21.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers