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())- A. 130 130 double(coffee+milk)
- B. 115 130 double(coffee)+milk
- C. 130 115 coffee+milk+double
- 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.
Practise more Software Engineering, Git and Cloud Basics questionsSoftware Engineering, Git and Cloud Basics: notes and key points
More Software Engineering, Git and Cloud Basics questions
- What does this Chain of Responsibility code print? python class Handler: def init(self, limit, name, nxt=None): self.limit, self.name…
- What does this Singleton implemented with a metaclass print? python class Meta(type): inst = {} def call(cls, a, k): if cls not in…
- This Observer code registers three listeners. What does it print? python class Subject: def init(self): self.obs = [] def attach(self, f)…
- A drawing app has 4 shape types and must render each through 3 back-ends (SVG, Canvas, PDF). Building one subclass per combination needs…
- A compiler has a stable set of AST node classes (Number, BinaryOp, Call, Variable) but keeps adding new operations: type-check…
- A file-manager must compute the total size of a folder, where a folder may contain files and other folders, and client code should call…