python – 将变量作为模块中的字符串进行访问

前端之家收集整理的这篇文章主要介绍了python – 将变量作为模块中的字符串进行访问前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

按照这里的其他帖子,我有一个函数,根据其名称打印出有关变量的信息.我想把它移到一个模块中.

@H_404_5@#python 2.7 import numpy as np def oshape(name): #output the name,type and shape/length of the input variable(s) #for array or list x=globals()[name] if type(x) is np.array or type(x) is np.ndarray: print('{:20} {:25} {}'.format(name,repr(type(x)),x.shape)) elif type(x) is list: print('{:20} {:25} {}'.format(name,len(x))) else: print('{:20} {:25} X'.format(name,type(t))) a=np.array([1,2,3]) b=[4,5,6] oshape('a') oshape('b')

输出

@H_404_5@a

我想把这个函数oshape()放到一个模块中,以便它可以重用.但是,放置在模块中不允许从主模块访问全局变量.我尝试过’import __main__’之类的东西,甚至存储函数globals()并将其传递给子模块.问题是globals()是一个函数,它专门返回调用它的模块的全局变量,而不是每个模块的不同函数.

@H_404_5@import numpy as np import olib a=np.array([1,6] olib.oshape('a') olib.oshape('b')

给我:

@H_404_5@KeyError: 'a'

额外的信息:
目标是减少冗余类型.稍微修改一下(我把它拿出去使问题更简单),oshape可以报告变量列表,所以我可以使用它:

@H_404_5@oshape('a','b','other_variables_i_care_about')

所以需要两次输入变量名称解决方案并不是我想要的.此外,只是传入变量不允许打印名称.考虑在长日志文件中使用它来显示计算结果&检查变量大小.

最佳答案
你的逻辑过于复杂,你应该自己传递数组,因为你也已经将变量名称作为字符串传递,所以你没有找到你无法访问的东西.但是如果你想让你的代码完全正常工作,你可以在模块上设置一个属性

@H_404_5@import numpy as np import olib a = np.array([1,3]) b = [4,6] olib.a = a olib.b = b olib.oshape('a') olib.oshape('b')

这将采取任何args并搜索从attrs运行代码的模块:

@H_404_5@import numpy as np import sys from os.path import basename import imp def oshape(*args): # output the name,type and shape/length of the input variable(s) # for array or list file_name = sys.argv[0] mod = basename(file_name).split(".")[0] if mod not in sys.modules: mod = imp.load_source(mod,file_name) for name in args: x = getattr(mod,name) if type(x) is np.array or type(x) is np.ndarray: print('{:20} {:25} {}'.format(name,x.shape)) elif type(x) is list: print('{:20} {:25} {}'.format(name,len(x))) else: print('{} {} X'.format(name,type(x)))

只需传递变量名称字符串:

@H_404_5@:~/$cat t2.py import numpy as np from olib import oshape a = np.array([1,6] c = "a str" oshape("a","b","c") :$python t2.py a

猜你在找的Python相关文章