gpt4 book ai didi

PythonWin 的 python 交互式 shell 调用构造函数两次?

转载 作者:行者123 更新时间:2023-11-28 21:31:02 25 4
gpt4 key购买 nike

在回答 Static class variables in Python

我注意到 PythonWin PyWin32 build 209.2 解释器似乎计算了两次?

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]
>>>

当 python 解释器做正确的事情时

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]
>>>

最佳答案

我的猜测如下。 PythonWin 编辑器为对象提供自动完成功能,即当您键入 myobject. 时,它会提供所有可用方法名称的小弹出窗口。所以我认为当你输入 X(). 时,它会在后台创建一个 X 的实例,并执行 dir 或类似的操作来找出对象的属性。

因此,构造函数只为每个对象运行一次,但为了给您交互性,它会在后台静默创建对象而不告诉您。

关于PythonWin 的 python 交互式 shell 调用构造函数两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/81191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com