CS FundamentalsVery hardProduct-company placement · Python interview
What does this Singleton implemented with a metaclass print?
What does this Singleton implemented with a metaclass print?
class Meta(type):
_inst = {}
def __call__(cls, *a, **k):
if cls not in cls._inst:
cls._inst[cls] = super().__call__(*a, **k)
return cls._inst[cls]
class Config(metaclass=Meta):
def __init__(self, env="dev"):
self.env = env
x = Config("prod")
y = Config("test")
print(x is y, y.env)- A. True test
- B. True prod
- C. False test
- D. False prod
Correct answer: B. True prod
The metaclass intercepts construction: the first call creates and caches the instance, and later calls return it without running __init__ again. So y is x and env stays 'prod' - a classic surprise when a Singleton silently ignores new arguments.
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
- 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…
- A text editor needs multi-level undo and redo, and also wants to queue and log user actions such as 'insert text' or 'delete line'. Which…
- A vending machine's behaviour for insertCoin() and selectItem() differs completely in the states Idle, HasCoin, Dispensing and SoldOut…