Challenge - 5 Problems
Instance Methods Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of instance method call
What is the output of this Python code?
Python
class Car: def __init__(self, brand): self.brand = brand def show_brand(self): return f"This car is a {self.brand}." my_car = Car("Toyota") print(my_car.show_brand())
Attempts:
2 left
💡 Hint
Look at how the instance method uses self to access the brand attribute.
✗ Incorrect
The method show_brand uses self.brand to get the brand of the car instance. Since my_car.brand is 'Toyota', the output is 'This car is a Toyota.'.
❓ Predict Output
intermediate2:00remaining
Instance method modifying attribute
What will be the value of x.speed after running this code?
Python
class Bike: def __init__(self): self.speed = 0 def accelerate(self, amount): self.speed += amount x = Bike() x.accelerate(10)
Attempts:
2 left
💡 Hint
The accelerate method adds the amount to the speed attribute.
✗ Incorrect
The accelerate method increases the speed attribute by the given amount. Initially speed is 0, after calling accelerate(10), speed becomes 10.
❓ Predict Output
advanced2:00remaining
Instance method with default argument
What is the output of this code snippet?
Python
class Counter: def __init__(self): self.count = 0 def add(self, n=1): self.count += n return self.count c = Counter() print(c.add()) print(c.add(5))
Attempts:
2 left
💡 Hint
The add method increases count by n, defaulting to 1 if no argument is given.
✗ Incorrect
First call c.add() adds 1 to count (0+1=1). Second call c.add(5) adds 5 (1+5=6). So outputs are 1 and 6.
❓ Predict Output
advanced2:00remaining
Instance method calling another instance method
What will this code print?
Python
class Person: def __init__(self, name): self.name = name def greet(self): return f"Hello, {self.name}!" def welcome(self): return self.greet() + " Welcome to the platform." p = Person("Alice") print(p.welcome())
Attempts:
2 left
💡 Hint
The welcome method calls greet and adds more text.
✗ Incorrect
The welcome method calls greet(), which returns 'Hello, Alice!'. Then it adds ' Welcome to the platform.' resulting in the full greeting.
🧠 Conceptual
expert2:00remaining
Understanding self in instance methods
Which statement about the use of self in instance methods is correct?
Attempts:
2 left
💡 Hint
Think about how Python passes the instance to methods.
✗ Incorrect
self is a conventional name for the first parameter of instance methods. It refers to the instance and is passed automatically by Python when calling the method.