简体   繁体   English

如何在Python中列出我自己定义的所有变量,不包括导入的变量?

[英]How to list all variables defined by myself in Python, excluding imported variables?

I know there are some ways to list all variable, such as locals(), globals(), dir(). 我知道有一些方法可以列出所有变量,例如locals(),globals(),dir()。 But they also list the variables imported from other modules, and make a very long list, which is hard to find variables defined by myself. 但是他们还列出了从其他模块导入的变量,并制作了一个很长的列表,很难找到我自己定义的变量。 So how should I list all variables defined by myself, better with their values? 那么我应该如何列出我自己定义的所有变量,更好地使用它们的值?

Here is an example: 这是一个例子:

import numpy
a=1
b=2
dir()

Then the result is: 然后结果是:

['In',
 'Out',
 '_',
 '_1',
 '_2',
 '_3',
 '_4',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '__package__',
 '_dh',
 '_i',
 '_i1',
 '_i2',
 '_i3',
 '_i4',
 '_i5',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'a',
 'b',
 'exit',
 'get_ipython',
 'numpy',
 'quit']

But I only want to see variables defined in this module, ie, a and b. 但我只想看到这个模块中定义的变量,即a和b。 How should I do that? 我该怎么办?

Save the result of locals() at the top of your module, after any imports. 在任何导入之后,将locals()的结果保存在模块的顶部。

Any new items that subsequently show up in locals() must have been defined by you. 随后显示在locals()任何新项目必须由您定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM