如何在python中访问给定变量的名称? [英] How do I access the name of a given variable in python?

查看:42
本文介绍了如何在python中访问给定变量的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 python 编程,需要访问我为对象提供的名称,以便能够将其作为字符串(与另一个字符串连接)传递.

我需要这样做的原因是我正在使用的程序迫使我创建一个全局(在我的例子中是一个字典)并且我正在编写一个函数来处理几个不同的对象(每个对象都有类似的属性集,例如对象 1 的长度为 2(在我的情况下表示 2 个神经元)标记为 0 和 1,每个都有 4 个属性 a、b、c、d.我想创建一个字典文件树"这些属性,但 object1 和 object 2 是同一类的 2 个实例,因此我需要将第一级键更改为NAME1_0"、NAME1_1"、NAME2_0"、NAME2_1").

def 初始化(神经元,输入):#初始化神经元组,参数是神经元(neurongroup)和输入(neurongroup)全局字典字典={}对于范围内的 x(0,len(neuron)):神经元[x].L=0神经元[x].G=0神经元[x].ron=1/周期神经元[x].roff=1/周期dict[x]={'tau_on':0.5,'非关闭':神经元[x].roff*0.5,'非关闭':神经元[x].ron*0.5,'Ni_on':ones(len(input))*qon*0.5,'Ni':ones(len(input))*qoff*0.5+ones(len(input))*qon*0.5,'p_current':0,'p_previous':0,'my_tau_on':[],'my_Non_off':[],'my_Noff_on':[],'my_Ni_on':[],'my_Ni':[],'my_p_on':[],'my_ron':[],'my_roff':[],'my_theta':[],'my_weights':[],'my_record_times':[]}dict['%s' % x, 神经元]=dict.pop(x)

不起作用,因为它没有给出分配给对象的名称,而只是给出对象本身的名称.对于我的问题的最小情况

NAME1=4def func(x): #创建'NAME1'的字符串打印x"功能(名称1)#output='NAME1'

解决方案

您可以对 globals() 中的名称进行反向查找:

<预><代码>>>>名称 1 = 4>>>def name_of(value):对于 k, v 在 globals().items() 中:如果 v 是值:返回 kraise KeyError('没有找到 %s' % 值的名称)>>>name_of(NAME1)'NAME1'

如果同一个对象被分配了多个名称,则只会返回一个名称.

如果您想搜索的范围比全局变量更广泛,请在 gc.get_referrers(value) 中查找字典并捕获所有匹配项:

<预><代码>>>>def names_of(value):'查找值的所有名称'结果 = []对于 gc.get_referrers(value) 中的 d:如果 isinstance(d, dict):对于 d.items() 中的 k, v:如果 v 是值:结果.append(k)返回结果>>>导入数学>>>馅饼 = math.pi>>>names_of(馅饼)['馅饼', '_pi', 'pi', 'pi']

I am programming in python and need to access the name I have given to an object so as to be able to pass this as a string (concatenated with another string).

The reason I need to do this is that the program I am using forces me to create a global (which in my case is a dictionary) and I am writing a function to work in general with several different objects (which each have similar sets of properties, eg. object 1 is of length 2 (signifying in my case 2 neurons) labelled 0 and 1 and each of these has 4 properties a,b,c,d. I want to create a "dictionary filetree" of these properties but both object1 and object 2 are 2 instances of the same class, therefore I need to change the first level keys to being 'NAME1_0, 'NAME1_1', 'NAME2_0', 'NAME2_1').

def Init(neuron,input):
#Initialises the neuron group, arguements are neuron (neurongroup) and input (neurongroup)
global dict
dict={}
for x in range(0,len(neuron)):
    neuron[x].L=0
    neuron[x].G=0
    neuron[x].ron=1/period
    neuron[x].roff=1/period
    dict[x]={'tau_on':0.5,
             'Non_off':neuron[x].roff*0.5,
             'Non_off':neuron[x].ron*0.5,
             'Ni_on':ones(len(input))*qon*0.5,
             'Ni':ones(len(input))*qoff*0.5+ones(len(input))*qon*0.5,
             'p_current':0,
             'p_previous':0,
             'my_tau_on':[],
             'my_Non_off':[],
             'my_Noff_on':[],
             'my_Ni_on':[],
             'my_Ni':[],
             'my_p_on':[],
             'my_ron':[],
             'my_roff':[],
             'my_theta':[],
             'my_weights':[],
             'my_record_times':[]}
     dict['%s' % x, neuron]=dict.pop(x)

does not work as it does not give the name assigned to the object but merely the name of the object itself. for a more minimal case of my problem

NAME1=4
def func(x):    #creates string of 'NAME1'
    print 'x'

func(NAME1)
#output='NAME1'

解决方案

Your could do a reverse lookup of the names in globals():

>>> NAME1 = 4
>>> def name_of(value):
        for k, v in globals().items():
            if v is value:
                return k
        raise KeyError('did not find a name for %s' % value)

>>> name_of(NAME1)
'NAME1'

If the same object has been assigned to more than one name, only one name will be returned.

If you want to search more broadly than just globals, look for the dicts in gc.get_referrers(value) and capture all matches:

>>> def names_of(value):
        'Find all names for the value'
        result = []
        for d in gc.get_referrers(value):
            if isinstance(d, dict):
                for k, v in d.items():
                    if v is value:
                        result.append(k)
        return result

>>> import math
>>> pie = math.pi
>>> names_of(pie)
['pie', '_pi', 'pi', 'pi']

这篇关于如何在python中访问给定变量的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆