ProgrammingVery hardProduct company OA
What is printed?
What is printed?
class C:
k = 5
def f(self, v=k):
return v
def g(self):
try:
return k
except NameError:
return "NE"
C.k = 9
print(C().f(), C().g(), C().k)- A. 9 9 9
- B. 5 9 9
- C. 9 NE 9
- D. 5 NE 9
Correct answer: D. 5 NE 9
Default values are evaluated once, while the class body executes, where k is visible: v defaults to 5, and rebinding C.k later does not change it. Method bodies do NOT see class-body names as plain variables (class scope is skipped by nested functions), so k inside g is looked up as a global, does not exist, and NameError is caught. C().k finds the class attribute, now 9.
More Python Programming questions
- What is printed? python d = {"a": 1} print(d.get("b", 0), "a" in d, 1 in d, d.get("b"))
- What is printed? python print(list("ab") + ["c"], tuple([1, 2]) 2)
- What is printed? python d = {"a": 1} try: d["k"] except KeyError as e: print(repr(e), e.args, len(d))
- What is printed? python print([x if x % 2 else -x for x in range(5)], [x for x in range(5) if x % 2 or x == 0])
- What is printed? python print(int(" -0012 "), int("1000"), float("1e3"), int("101", 2), int(-2.9))
- What is printed? python def g(): try: yield 1 yield 2 finally: print("cleanup", end=" ") it = g() print(next(it), end=" ") it.close()…