How do I create a function that will create a global (and assign it a value) with a name that contains the name of the argument given to it?
I'm using Python and am trying to create a function that will look at the name o开发者_StackOverflow中文版f 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.
It sounds like a terrible idea...
def func(prefix):
g = globals()
g[prefix + '_tomato'] = 123
g[prefix + '_broccoli'] = 456
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.
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?
tau_some_argument['object1'] = some_value1
ron_some_argument['object1'] = some_value2
精彩评论