Python,打印所有绑定变量的名称和值

4 投票
4 回答
2425 浏览
提问于 2025-04-16 04:32

有没有办法让Python打印出所有绑定变量的名字和它们的值?

(不需要重新设计程序,把它们都存到一个列表里)

4 个回答

0
dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

2

globals()locals() 这两个函数应该能满足你的需求。

2

是的,你可以这样做,虽然这个方法有点不太干净,但在调试等情况下还是挺有用的。

from pprint import pprint

def getCurrentVariableState():
    pprint(locals())
    pprint(globals())

撰写回答