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__)- A. 5 k m W False
- B. 10 kk m W False
- C. 10 kk kk W False
- 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
- What is printed? python def counter(): n = 0 def inc(k=1): nonlocal n n += k return n return inc c1, c2 = counter(), counter() g = (c1(i)…
- What is printed? python def f(): out = [] for i in range(4): try: if i == 1: continue if i == 2: raise KeyError(i) if i == 3: return out…
- What is printed? python rows = [("x", 2), ("y", 1), ("z", 2), ("w", 1), ("v", 3)] a = sorted(rows, key=lambda r: r[1], reverse=True) b =…
- What is printed? python class P: def init(self, x, y): self.x, self.y = x, y def eq(self, o): return self.x == o.x def hash(self): return…
- What is printed? python it = iter(range(10)) a = list(zip(it, "ab")) b = next(it) c = [x for x in it if next(it, 0) % 3] print(a, b, c)
- What is printed? python def tag(t): print("make", t, end=" ") def deco(fn): print("wrap", t, end=" ") def inner(a): return f"<{t}>" +…