ProgrammingHardAccenture pattern

What is printed?

What is printed?
x = 10
class C:
    x = 20
    def m(self):
        return x
c = C()
print(c.m(), C.x)
  1. A. 20 20
  2. B. 10 10
  3. C. 20 10
  4. D. 10 20

Correct answer: D. 10 20

Inside method m, the bare name x refers to the enclosing (module-level/global) scope, NOT the class attribute -- class bodies don't create an enclosing scope for their methods. So m() returns the global x, 10, while C.x (accessed via the class) is the class attribute, 20.

More Python Programming questions

Exams that ask this topic