CS FundamentalsVery hardProduct-company placement · Python interview

What does this Decorator-pattern code print?

What does this Decorator-pattern code print?
class Coffee:
    def cost(self): return 50
    def desc(self): return "coffee"
class AddOn:
    def __init__(self, inner): self.inner = inner
class Milk(AddOn):
    def cost(self): return self.inner.cost() + 15
    def desc(self): return self.inner.desc() + "+milk"
class Double(AddOn):
    def cost(self): return self.inner.cost() * 2
    def desc(self): return "double(" + self.inner.desc() + ")"
print(Double(Milk(Coffee())).cost(), Milk(Double(Coffee())).cost(), Milk(Double(Coffee())).desc())
  1. A. 130 130 double(coffee+milk)
  2. B. 115 130 double(coffee)+milk
  3. C. 130 115 coffee+milk+double
  4. D. 130 115 double(coffee)+milk

Correct answer: D. 130 115 double(coffee)+milk

Wrappers apply from the inside out: Double(Milk(Coffee)) = (50 + 15) x 2 = 130, while Milk(Double(Coffee)) = 50 x 2 + 15 = 115, described as double(coffee)+milk. Decorator order matters when the added behaviours do not commute.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic