Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q4 of Q15
Python - Encapsulation and Data Protection
What will be the output of this code?
class Car:
    def __init__(self):
        self.__speed = 0
    def set_speed(self, speed):
        self.__speed = speed
    def get_speed(self):
        return self.__speed

car = Car()
car.set_speed(50)
print(car.get_speed())
ANone
B0
CError: AttributeError
D50
Step-by-Step Solution
Solution:
  1. Step 1: Understand private variable usage

    The variable __speed is private but accessible inside class methods.
  2. Step 2: Trace method calls and output

    set_speed sets __speed to 50, get_speed returns 50, so print outputs 50.
  3. Final Answer:

    50 -> Option D
  4. Quick Check:

    Private variable accessed via methods = 50 [OK]
Quick Trick: Use getter/setter to access private variables [OK]
Common Mistakes:
MISTAKES
  • Expecting direct access to __speed outside class
  • Thinking private variables cannot be changed
  • Confusing initial value with updated value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes