CS FundamentalsVery hardProduct-company placement · Python interview
What does this Prototype-style code print?
What does this Prototype-style code print?
import copy
class Doc:
def __init__(self, title, tags):
self.title = title
self.tags = tags
a = Doc("v1", ["draft"])
b = copy.copy(a)
c = copy.deepcopy(a)
b.title = "v2"
b.tags.append("review")
c.tags.append("final")
print(a.title, a.tags, len(c.tags))- A. v1 ['draft'] 2
- B. v2 ['draft', 'review'] 2
- C. v1 ['draft', 'review'] 2
- D. v1 ['draft', 'review', 'final'] 3
Correct answer: C. v1 ['draft', 'review'] 2
A shallow copy shares the same list, so b.tags.append changes a.tags; rebinding b.title does not touch a. The deep copy has its own list ['draft', 'final'], so its length is 2 and a is unaffected by it.
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 Decorator-pattern code print? python class Coffee: def cost(self): return 50 def desc(self): return "coffee" class AddOn…
- 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…