如何创建一个函数,该函数将创建一个全局变量(并为其分配一个值),其名称包含为其提供的参数名称?
我正在使用Python,并尝试创建一个函数,该函数将查看作为参数给出的对象的名称,并(除其他外)创建一些包含该名称的全局变量, 例如:
object1=someclass(args,kwds) #the object is an instance of a class that is given a certain name (e.g.object1)
def somefunc(some_argument):
global tau_some_argument
global ron_some_argument #e.t.c. for other variables (I also would like to assign some variables etc)
tau_some_argument=some_value1
ron_some_argument=some_value2
print ron_some_argument
print tau_some_argument
现在如果我调用这个函数,我想要发生的事情如下: 当我调用时,
somefunc(object1)
我希望它创建一些名为 tau_object1、ron_object1 的全局变量并为它们分配值(打印语句不相关),类似地,如果我调用
somefunc(object2)
其中 object2 是类的另一个实例,我希望它创建全局变量: tau_object2、ron_object2 ,目前该函数只是创建名为 tau_some_argument 的全局变量(从代码中可以明显看出)。
现在我在某处读到 python 对象的名称是不可变的,除非它们是类或函数,所以我不知道如何做到这一点,从阅读中我感觉我可能需要使用元类,但这感觉就像这是一种过于复杂的方式来做一些应该相对容易的事情。
提前致谢。
I'm using Python and am trying to create a function that will look at the name of the object that is given as an argument and (among other things) create some globals that contain this name,
for example:
object1=someclass(args,kwds) #the object is an instance of a class that is given a certain name (e.g.object1)
def somefunc(some_argument):
global tau_some_argument
global ron_some_argument #e.t.c. for other variables (I also would like to assign some variables etc)
tau_some_argument=some_value1
ron_some_argument=some_value2
print ron_some_argument
print tau_some_argument
now what I want to happen if I call this function is as follows:
when I call
somefunc(object1)
I would like it to create some globals named tau_object1, ron_object1 and assign them values (the print statements are irrelevant), similarly if i called
somefunc(object2)
where object2 is another instance of a class I would like it to create globals: tau_object2, ron_object2, at the moment the function simply creates globals named tau_some_argument (as is obvious from the code).
Now I read somewhere that the names of python objects are immutable, unless they are a class or function so I don't know how to do this, from reading I get the feeling that I may need to use meta-classes but this feels like it's an overly complicated way of doing something that should be relatively easy.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这听起来是一个糟糕的想法......
无论你在做什么,它都可以用字典、数组和其他对象来完成,方式不像上面的方法那样脆弱。
It sounds like a terrible idea...
Whatever you are doing, it can probably be done with dictionaries, arrays, and other objects in a way that isn't fragile like the above method.
我对 python 不太确定,但是你不能只声明一个全局数组并简单地创建按对象名称索引的对象作为字符串吗?
I'm not so sure about python but can't you just declare a global array and simply create the object indexed by the name of the object as a string?