Python Programming - Objects

Exercise : Objects - General Questions
  • Objects - General Questions
21.
Consider the following Python code:
class Animal:
    def __init__(self, species, legs):
        self.species = species
        self.legs = legs

    def sound(self):
        return "Unknown sound"
If you create an instance of the `Animal` class called dog with species "Dog" and legs 4, what will be the result of calling dog.sound()?
"Meow"
"Woof"
"Unknown sound"
None
Answer: Option
Explanation:
The sound method returns "Unknown sound" by default. It can be overridden in derived classes to provide specific sound implementations.

22.
What does the __repr__ method in Python classes typically represent?
String representation for print()
Length of the object
Equality comparison
Object serialization
Answer: Option
Explanation:
The __repr__ method is used to define the string representation of an object. It is called by the repr() function and is typically used for debugging and development.

23.
Consider the following Python code:
class Circle:
    def __init__(self, radius):
        self.radius = radius

    def calculate_circumference(self):
        return 2 * 3.14 * self.radius
If you create an instance of the `Circle` class called small_circle with a radius of 2, what will be the result of calling small_circle.calculate_circumference()?
6.28
12.56
18.84
25.12
Answer: Option
Explanation:
The calculate_circumference method calculates the circumference of the circle using the formula 2 * 3.14 * radius. For the given instance, it would be 2 * 3.14 * 2 = 12.56.

24.
In Python, what is the purpose of the __hash__ method in a class?
To create a hash value for the object
To check if two objects are equal
To delete the class object
To serialize the object
Answer: Option
Explanation:
The __hash__ method is used to define the hash value for an object. It is called by functions like hash().

25.
Consider the following Python code:
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def give_raise(self, amount):
        self.salary += amount
If you create an instance of the `Employee` class called john with a salary of 50000 and then call john.give_raise(5000), what will be the updated salary?
55000
5000
45000
None
Answer: Option
Explanation:
The give_raise method increases the salary attribute by the specified amount. In this case, it would be 50000 + 5000 = 55000.