Exercise: Python

Questions for: Objects

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?
A:
55000
B:
5000
C:
45000
D:
None
Answer: A
The give_raise method increases the salary attribute by the specified amount. In this case, it would be 50000 + 5000 = 55000.
In Python, what is the purpose of the __hash__ method in a class?
A:
To create a hash value for the object
B:
To check if two objects are equal
C:
To delete the class object
D:
To serialize the object
Answer: A
The __hash__ method is used to define the hash value for an object. It is called by functions like hash().
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()?
A:
6.28
B:
12.56
C:
18.84
D:
25.12
Answer: B
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.
What does the __repr__ method in Python classes typically represent?
A:
String representation for print()
B:
Length of the object
C:
Equality comparison
D:
Object serialization
Answer: A
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.
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()?
A:
"Meow"
B:
"Woof"
C:
"Unknown sound"
D:
None
Answer: C
The sound method returns "Unknown sound" by default. It can be overridden in derived classes to provide specific sound implementations.
Ad Slot (Above Pagination)
Quiz