ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class H:
__slots__ = ["a", "b"]
h = H()
h.a = 1
try:
h.c = 2
except AttributeError:
print("AttributeError")
print(h.a)- A. AttributeError 1
- B. 2 1
- C. AttributeError 2
- D. 1 1
Correct answer: A. AttributeError 1
__slots__ restricts instances to only the named attributes (a, b) and removes the usual per-instance __dict__, so assigning to the undeclared attribute c raises AttributeError, while a was declared and assigns fine.
More Python Programming questions
- What is printed? python class K: x = 10 def method(self): x = 20 return x print(K().method(), K.x)
- What is printed? python class Counter: def init(self, n): self.n = n def iter(self): self.i = 0 return self def next(self): if self.i >=…
- What is printed? python class Box: def init(self, items): self.items = items def len(self): return len(self.items) def contains(self, x)…
- What is printed? python class D: def getitem(self, key): if isinstance(key, slice): return f"slice {key.start}:{key.stop}:{key.step}"…
- What is printed? python try: try: 1 / 0 except ZeroDivisionError: raise RuntimeError("r") except RuntimeError as e: print(e…
- What is printed? python try: raise ValueError("x") from None except ValueError as e: print(e.cause, e.suppresscontext)