Bird
Raised Fist0

You want to convert this procedural code into an object-oriented style. Which class design correctly encapsulates the data and behavior?

hard🚀 Application Q15 of Q15
Python - Object-Oriented Programming Foundations
You want to convert this procedural code into an object-oriented style. Which class design correctly encapsulates the data and behavior?
# Procedural code
def area_rectangle(width, height):
    return width * height

w = 5
h = 3
print(area_rectangle(w, h))
Aclass Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height
Bclass Rectangle: def area(width, height): return width * height
Cclass Rectangle: def __init__(self): pass def area(self): return width * height
Dclass Rectangle: def __init__(self, width, height): return width * height
Step-by-Step Solution
Solution:
  1. Step 1: Identify data and behavior to encapsulate

    The procedural code uses width and height as data and area_rectangle as behavior. In OOP, these should be inside a class.
  2. Step 2: Check class options for correct encapsulation

    class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height stores width and height as instance variables and defines area() method using them. Other options either miss self, lack data storage, or misuse return in constructor.
  3. Final Answer:

    class Rectangle with __init__ storing width and height, and area method using them -> Option A
  4. Quick Check:

    OOP encapsulates data and behavior in class [OK]
Quick Trick: Store data in __init__, use methods for behavior [OK]
Common Mistakes:
MISTAKES
  • Not using self for instance variables
  • Returning values from __init__
  • Defining methods without self parameter

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes