Bird
0
0

Given a class Rectangle with attributes width and height, write the correct way to double the width attribute value.

hard📝 Application Q9 of 15
Python - Classes and Object Lifecycle
Given a class Rectangle with attributes width and height, write the correct way to double the width attribute value.
ABoth A and C
Brect.width = rect.width * 2
Crect.width *= 2
Drect.set_width(rect.width * 2)
Step-by-Step Solution
Solution:
  1. Step 1: Understand attribute modification

    You can change an attribute by assigning a new value, either by multiplying and assigning or using the shorthand operator.
  2. Step 2: Evaluate options

    rect.width = rect.width * 2 uses explicit multiplication and assignment. rect.width *= 2 uses the shorthand operator. Both correctly double the width. rect.set_width(rect.width * 2) assumes a method that may not exist.
  3. Final Answer:

    Both A and C -> Option A
  4. Quick Check:

    Both assignment styles work for attribute modification = Both A and C [OK]
Quick Trick: Use *= or = with expression to modify attributes [OK]
Common Mistakes:
  • Assuming only one syntax works
  • Calling non-existent setter methods
  • Confusing attribute with method calls

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes