问题
Why i can't get the values in the items in dir() with loop:
for item in dir():
print(item)
It just print
__builtins__
__doc__
__loader__
__name__
__package__
__spec__
So, how can i use loop to print the value in item, i.e "__main__"
in __name__
Thanks!
回答1:
Calling dir without the argument is logically equivalent to list(locals())
, as in getting the list of names of variables in the current namespace (keys of locals()
dictionary).
You'd use the items
method of locals()
instead:
In [5]: for name, value in list(locals().items()):
...: print(name, value)
...:
回答2:
vaultah's answer is best, I think, but you could also use eval to get the values:
for item in dir():
print('{} : {}'.format(item, eval(item)))
There is usually a lot of stigma regarding the use of eval
(it's dangerous!) and I will probably be downvoted for this answer, however, I think that it OK in this limited case.
来源:https://stackoverflow.com/questions/28379099/how-to-use-loop-to-get-values-in-dir