Change tactics or give up: It's a crossroads many teachers face when students don't understand the code.

I can never forget an evening late into a semester of my Introduction to Python course, during which I asked my students a question about user-defined classes. Here’s the code I had put on the board:

1

2

3

4

5

6

7

8

9

10

11

classMyClass(object):

var=0

def __init__(self):# called

MyClass.var=MyClass.var+1

x=MyClass()# new instance created

y=MyClass()# new instance created

As new information for this particular lesson, I informed them that every time a new MyClass instance is created, the __init__() method is called implicitly. In other words, the code above calls __init__() twice, and in executing the code in __init__(), the variable MyClass.var is being incremented — so this is also happening twice.

So, I asked them: after the above code is executed, what is the value of MyClass.var?