我可以将 self 设置为被忽略的东西吗?

我正在使用 Python 类中的代码编写代码。例如,像这样:


    self.ulist = {}

    for i in self.vlist:

        if i not in self.ulist:

            self.ulist[i] = {}

            self.ulist[i]['appears'] = []

我测试代码的方式是有时我只想将代码片段复制到 Jupyter 或 ipython 中并运行代码。


我可以将 self 设置为什么,使其不会给出


name 'self' is not defined

错误?我知道您可以将 self 设置为任何东西,因为 self 是一个变量,我们可以将“self”设置为忽略它并将变量self.ulist, self.vlist视为 的东西ulist, vlist吗?


慕森王
浏览 250回答 1
1回答

千万里不及你

实际上,任何用户定义的对象都可以(没有定义 a __slots__)。Python 用户定义的对象很乐意接受您希望分配给它们的任何属性。或者,您也可以只使用一个SimpleNamespace对象:In [1]: from types import SimpleNamespaceIn [2]: self = SimpleNamespace()In [3]:&nbsp; &nbsp; &nbsp;self.vlist = {}&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;for i in self.vlist:&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if i not in self.ulist:&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.ulist[i] = {}&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.ulist[i]['appears'] = []&nbsp; &nbsp;...:In [4]: selfOut[4]: namespace(vlist={})至少有一个很好的开箱即用的印刷表示。但同样,你总是可以这样做:In [5]: class Foo: passIn [6]: self = Foo()In [7]:&nbsp; &nbsp; &nbsp;self.vlist = {}&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;for i in self.vlist:&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if i not in self.ulist:&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.ulist[i] = {}&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.ulist[i]['appears'] = []&nbsp; &nbsp;...:In [8]: selfOut[8]: <__main__.Foo at 0x105fde048>In [9]: self.vlistOut[9]: {}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python