获取当前加载的变量
函数dir()会列出所有加载的环境变量,如:
a = 2
b = 3
c = 4
print(dir())
会回来
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'c']
在下面找到dir 的文档所说的内容:
目录(...)
dir([object]) -> 字符串列表
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.
获取变量方法和属性
您还可以使用dir() 列出与对象关联的方法和属性,因为您应该使用:dir(<name of object>)
获取当前加载的变量的大小
如果您希望评估已加载变量/对象的大小,您可以使用sys.getsizeof(),例如:
sys.getsizef(a)
sys.getsizof(<name of variable>)
sys.getsizeof() 获取对象的大小(以字节为单位)(请参阅this post 了解更多信息)
结束
你可以将这个功能组合在某种循环中
import sys
a =2
b = 3
c = 4
d = 'John'
e = {'Name': 'Matt', 'Age': 32}
for var in dir():
print(var, type(eval(var)), eval(var), sys.getsizeof(eval(var)))
希望有帮助!