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

Exams that ask this topic