您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:21:54 python 字数 5319 阅读 513 来源 www.jb51.cc/python

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

概述

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

#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                    
  
   ndarray'>    (3,)
b                    
   
  

我想把这个函数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                    
  
   ndarray'>    (3,)
b                    
   
  

总结

以上是编程之家为你收集整理的python – 将变量作为模块中的字符串进行访问全部内容,希望文章能够帮你解决python – 将变量作为模块中的字符串进行访问所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶