ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class Meter:
    unit = "m"
    def __init__(self): self.__dict__["v"] = 1
    def __getattr__(self, name): return name.upper()
    def __setattr__(self, name, val): self.__dict__[name] = val * 2
m = Meter()
m.v = 5
m.unit = "k"
print(m.v, m.unit, Meter.unit, m.w, "w" in m.__dict__)
  1. A. 5 k m W False
  2. B. 10 kk m W False
  3. C. 10 kk kk W False
  4. D. 10 kk m W True

Correct answer: B. 10 kk m W False

__setattr__ intercepts EVERY attribute assignment on the instance, so m.v = 5 stores 10 and m.unit = 'k' stores 'kk' in the instance dict – the class attribute Meter.unit is untouched ('m'). __getattr__ is only a fallback, called after normal lookup fails: m.v and m.unit are found normally, m.w is not, so it returns 'W' without creating anything in __dict__. Output: 10 kk m W False.

More Python Programming questions

Exams that ask this topic