首页 > 解决方案 > iPython中神秘分配的构造函数参数

问题描述

这是我对 StackOverflow 的第一个问题。如果这个问题的格式不标准,请随时告诉我。

在我发现iPython之后,我一直在从 Matlab 过渡到 Python 。我使用VSCode和 Jupyter 界面以及“# %%”标头来获得交互式控制台。到目前为止,我热爱一切,我觉得我的工作需要完全过渡。

我在初始化类实例时遇到了一些神秘的问题。

假设我们有两个重新创建问题的最小文件:

主文件

# %%
%reset -f
from dummy import Dummy
dummy = Dummy()
print('created = %s' % dummy.others)
dummy.receive('something')
print('received = %s' % dummy.others)

假人.py

class Dummy():
    def __init__(self, others=[]):
        self._others = others
        pass

    def receive(self, value):
        self._others.append(value)

    @property
    def others(self):
        return self._others

当我在重新启动 Jupyter 内核后第一次运行 main.py 时,我得到了

created = []
received = ['something']

这是完全可以预料的。但是,如果我再次运行它,我会得到

created = ['something']
received = ['something', 'something']

表示“虚拟”变量未按应有的方式初始化。

为了追查源头,我更改了脚本,以便

main.py(调试)

# %%
%reset -f

from dummy import Dummy
try:
    print(dummy.others)
except:
    print('dummy not found')

dummy = Dummy()
print('created = %s' % dummy.others)
dummy.receive('something')
print('received = %s' % dummy.others)

dummy.py(调试)

class Dummy():
    def __init__(self, others=[]):
        print('input = %s' % others)
        self._others = others
        print('internal = %s' % self._others)
        pass

    def receive(self, value):
        self._others.append(value)

    @property
    def others(self):
        return self._others

当我在重新启动内核后运行主脚本时,我得到

dummy not found
input = []
internal = []
created = []
received = ['something']

和下面的又一次运行

dummy not found
input = ['something']
internal = ['something']
created = ['something']
received = ['something', 'something']

很明显,在“%reset -f”之后成功删除了“dummy”变量,但不知何故,Dummy 构造函数中的输入参数“others”被分配给先前分配的,而不是“[]”。

但为什么?

当我如下更改 dummy.py 中的“def receive(self, value)”时,我不再有问题了:

def receive(self, value):
    self._others = self._others + [value]

但同样,如果我理解正确的话,这种变化是可变的。它应该影响构造函数中的输入参数分配。

此外,当 Dummy 类位于同一文件 (main.py) 中时,不会出现此问题

你能告诉我我错过了什么吗?

编辑: 我现在明白我应该小心可变的初始化参数。但我的另一个基本问题是为什么 iPython 中的“%reset -f”没有清除所有内容。它确实删除了虚拟变量,但初始化参数“others”被神秘地分配给了前一个。魔法不是应该删除所有东西吗?

标签: pythonvisual-studio-codeipython

解决方案


这是一个正确的dummy.py脚本,没有可变参数作为默认值:

class Dummy():
    def __init__(self, others=None):
        self._others = others or []
        pass

    def receive(self, value):
        self._others.append(value)

    @property
    def others(self):
        return self._others

输出:

created = []
received = ['something']

推荐阅读