python - bpython -i & 命名空间

标签 python namespaces ipython interactive bpython

我似乎无法在任何地方找到这个答案。

举个简单的例子:

# myclass.py
class MyClass:
    def __init__(self):
        print 'test'

def main():
    my_class_instance = MyClass()

if __name__ == '__main__':
    main()

some_var = 'i exist!  ... but I think I'm in global namespace?'

如果我运行 bpython -i myclass.py,我会执行该程序并进入 bpython 环境。无论我在哪个命名空间 - my_class_instance 都不存在。但是, some_var 确实存在 - main 函数本身也是如此。

无论如何,当我进入该交互式提示时,我可以将存在于该主函数中的任何对象拉入我所在的命名空间中吗?或者还有什么我应该做的吗?

最佳答案

my_class_instancemain的命名空间,因此您无法在 main 之外看到它.改用全局:

my_class_instance = None

def main():
    global my_class_instance

    my_class_instance = MyClass()

关于python - bpython -i & 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7223829/

相关文章:

python - 根据搜索字符串从多行文本中捕获一行

Python + lxml : how to find the namespace of a tag?

python - 检测 python 脚本是从 ipython shell 运行,还是从命令行运行

python - 将工作目录设置为笔记本目录

python - Scipy 的 fftpack dct 和 idct

python - 删除 VSCode 中 Jupyter 单元格上方的按钮行

python - Pandas 数据框 : how to sentence into words and select rows that have more than 10 words?

python - `__import__(' pkg_resources').declare_namespace(__name__)` 有什么作用?

xml - 何时使用 W3C 的 xmlns 和 xmlns :xsi namespaces?

sql-server - 从 Python 连接到 SQL Server