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)
  1. A. AttributeError 1
  2. B. 2 1
  3. C. AttributeError 2
  4. 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

Exams that ask this topic