加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 22:45:06 所属栏目:Python 来源:网络整理
导读:按照这里的其他帖子,我有一个函数,根据其名称打印出有关变量的信息.我想把它移到一个模块中. #python 2.7import numpy as npdef oshape(name): #output the name,type and shape/length of the input variable(s) #for array or list x=globals()[name] if t

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

#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')

输出:

a                    

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

import numpy as np
import olib

a=np.array([1,6]

olib.oshape('a')
olib.oshape('b')

给我:

KeyError: 'a'

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

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

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

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

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运行代码的模块:

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)))

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

:~/$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                    

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读