pythonpython-2.xactivestate

PythonWin's python interactive shell calling constructors twice?


While answering Static class variables in Python

I noticed that PythonWin PyWin32 build 209.2 interpreter seems to evaluate twice?

PythonWin 2.5 (r25:51908, Mar  9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> class X:
...     l = []
...     def __init__(self):
...         self.__class__.l.append(1)
...         
>>> X().l
[1, 1]
>>> 

while the python interpreter does the right thing

C:\>python
ActivePython 2.5.0.0 (ActiveState Software Inc.) based on
Python 2.5 (r25:51908, Mar  9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class X:
...   l = []
...   def __init__(self):
...     self.__class__.l.append(1)
...
>>> X().l
[1]
>>>

Solution

  • My guess is as follows. The PythonWin editor offers autocomplete for an object, i.e. when you type myobject. it offers a little popup of all the availble method names. So I think when you type X(). it's creating an instance of X in the background and doing a dir or similar to find out the attributes of the object.

    So the constructor is only being run once for each object but to give you the interactivity it's creating objects silently in the background without telling you about it.