Bird
0
0

You have this procedural code:

hard📝 Application Q8 of 15
Python - Object-Oriented Programming Foundations
You have this procedural code:
def perimeter(length, width):
    return 2 * (length + width)

print(perimeter(4, 7))

Which class design correctly encapsulates this behavior in an object-oriented style?
Aclass Rectangle: def __init__(self, length, width): self.length = length self.width = width def perimeter(self): return 2 * (self.length + self.width)
Bclass Rectangle: def perimeter(length, width): return 2 * (length + width)
Cclass Rectangle: def __init__(self): pass def perimeter(self, length, width): return 2 * (length + width)
Dclass Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width
Step-by-Step Solution
Solution:
  1. Step 1: Identify encapsulation

    The class should store length and width as attributes and provide a method to calculate perimeter.
  2. Step 2: Evaluate options

    class Rectangle: def __init__(self, length, width): self.length = length self.width = width def perimeter(self): return 2 * (self.length + self.width) correctly initializes attributes and defines perimeter using them.
  3. Step 3: Eliminate incorrect options

    class Rectangle: def perimeter(length, width): return 2 * (length + width) lacks self and proper method structure; class Rectangle: def __init__(self): pass def perimeter(self, length, width): return 2 * (length + width) requires parameters in method instead of attributes; class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width defines area, not perimeter.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Attributes + method using self encapsulate behavior [OK]
Quick Trick: Use attributes and methods with self for encapsulation [OK]
Common Mistakes:
  • Not using self in method parameters
  • Passing parameters to methods instead of using attributes
  • Confusing area and perimeter methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes