attribue with dynamic variable name [duplicate] - python

This question already has answers here:
What is getattr() exactly and how do I use it?
(14 answers)
Closed 1 year ago.
another dynamic variable question, but different from other seen imho.
class MyClass:
myvarA="alfa"
myvarB="beta"
myvarC="gamma"
myobj=MyClass()
for var in ["A", "B", "C"]:
print("{}\n".format("myobj.myvar{}".format(var)))
My goal: print all attributes values in oneline using format myvar+variable as var name.
print in last line, prints "myobj.myvarA..B..C" instead of values
many thanks

You generally don't want to do that, you'll want to use a dict if you need "dynamic variable names".
Anyway, you can do this with getattr():
class MyClass:
myvarA = "alfa"
myvarB = "beta"
myvarC = "gamma"
myobj = MyClass()
for var in ["A", "B", "C"]:
var_name = f"myvar{var}"
print(getattr(myobj, var_name))

Related

How to add character or a number to a variable in python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I have some list like:
all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]
And I want to print it out like
num = 0
print(all+num)
But it didn't work.
How to add a character or a number to a variable name?
Hmm, I am pretty sure that you do not need nor really want it, but Python has provision for computing a variable name. Simply it is a rather advanced feature and the normal way is to use mappings (dict) or sequence (list or tuple) containers.
Here, you would use:
all = []
all.append([['mortem' 'cliffi' 'gear' 'lerp' 'control']])
all.append([['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']])
num = 0
print(all[0])
BTW, this syntax is weird, because you are essentially concatenating adjacent litteral string...
But if you really, really need it you can build a interpolator of variables:
def getvar(name):
if name in locals():
return locals()[name]
elif name in globals():
return globals()[name]
else:
raise NameError(repr(name) + ' is not defined')
You can then do:
all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]
num = 0
print(getvar("all%d" % num))
and get as expected:
[['mortemcliffigearlerpcontrol']]
You can use eval() for that.
eval('print(all{})'.format(num))
But this is really bad style. Don't do this. You should refactor your code and use for loops to go through your lists e.g.
all = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all.append(['video' 'player' 'stori' 'book' 'think' 'narr' 'kill'])
for l in all:
print(l)
Leaving aside how bad an idea it might be (probably really bad), variable names are just keys in a Python dict. A one-line solution might be:
vars()[new_name] = vars().pop(old_name)
for global variables, and
vars(some_obj)[new_name] = vars(some_obj).pop(old_name)
for variables of some_obj object.

Do stuff with variable that has the same name of a string [duplicate]

This question already has answers here:
How to use string value as a variable name in Python? [duplicate]
(3 answers)
How do I create variable variables?
(17 answers)
Closed 4 years ago.
let's say I have a variable called "x" and a string that has the value of "x" (string1 = "x"). How do I do stuff with the variable through the string?
For example change the variable's value or call a method if it's an object?
Thanks in advance
Variables are available through dictionaries locals() and globals(). If you want to access a particular variable by it's spring name, you can do e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x]
'hello'
You can also assign back to the variable using this approach, e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x] = 'something else'
>>> my_var
'something else'
Since functions are objects in Python, you can access any locally available functions in the same manner to call them.
>>> def my_test_function(n):
>>> return n*8
Accessing the method and calling it.
>>> locals()['my_test_function'](4)
32
For accessing attributes of objects by their name you can use getattr(), and setattr() to set them. For example, creating an object with a single property called your_prop.
class Example:
your_prop = 2
a = Example()
The value is available via your_prop.
>>> a.your_prop
2
The property can be accessed via name using getattr
>>> getattr(a, 'your_prop')
2
The property can be set using setattr:
>>> setattr(a, 'your_prop', 5)
>>> a.your_prop
5
Ok, let's suppose that you have lots of different functions: Aoo(), Boo(), Coo()... and let's suppose that you want to specify which of them to call via command line argument.
Now, that argument will be a string, so you need to call a function through its name, but you do not know in advance the name of the function.
One possible solution is to use exec():
def boo():
print("boo function")
def coo():
print("coo function")
Now:
argument = "boo"
exec(argument + "()")
>>> boo function
and
argument = "coo"
exec(argument + "()")
>>> coo function
It depends what you're trying to do, but you can scoop up whatever x is pointing to with locals() or globals():
def x(k):
return k + 1
string1 = "x"
the_function_x = locals()[string1]
print(the_function_x(3))
outputs 4 (it called the x function by utilizing string1).

Python how to change "existing" variable [duplicate]

This question already has answers here:
Global Variable in Python
(2 answers)
Closed 5 years ago.
I have a little python application, and declared at the top of the application a string called lastMsg, in a function, this string should be changed, but instead of changing the existing string, it creates a new string, how can I change the old string?
If I guessed correctly what you are trying to do (do share some code to further explain your answer):
You need to use the global keyword to specify you want to change the global variable.
myVar = "1"
def myFun():
global myVar
myVar = "2"
print(myVar)
myFun()
print(myVar)
Should print:
1
2
It's not quite clear what you're asking.
I think you mean this:
lastMsg = "some string"
def a_function():
lastMsg = "new value"
If so, you can change it using the global keyword:
lastMsg = "some string"
def a_function():
global lastMsg
lastMsg = "new value"

python select a function based on the value in a dictionary [duplicate]

This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 6 years ago.
I want to select a function based on the value of a dictionary:
dict = {"func_selector":"func1", "param_value":"some_value"}
# defined a function
def func1(param):
# some function code
Now, I want to select the function based on the value of some key, so that it can achieve something like:
# calling a function based on some dict value
dict["func_selector"](dict["param_value"])
The syntax is probably wrong, but I am wondering if it is possible to do that in Python or something similar.
Try storing the value of the function in the dictionary, instead of its name:
def func1(param):
print "func1, param=%r" % (param,)
d = {"func_selector":func1, "param_value": "some value"}
Then you can say:
>>> d['func_selector'](d['param_value'])
func1, param='some value'
The best approach IMO is do it like this
def func1(param):
#code
some_value = ... #The value you need
my_dict = {"func_selector": func1, "param_value": some_value }
And then
my_dict["func_selector"](my_dict["param_value"])
Now, if you only have the name of the function you need to call getattr
And call it
getattr(my_class, my_dict["func_selector"])(my_dict["param_value"])
my_class is the class which contains the method. If it's not in a class I think you can pass self

Is there a way to append an integer to the end of a variable name in python [duplicate]

This question already has answers here:
How to create an unknown amount of variables in python
(6 answers)
Closed 9 years ago.
after much googling i now ask. Is there a way to append an integer to the end of a variable name. Essentially creating a new variable with each iteration of a for loop. IE:
def parser(lst):
count = 0
for obj in lst:
if isinstance(obj,list):
parser(obj)
else:
for string in obj:
var+count = o
This is what i get when i try to run above code:
SyntaxError: can't assign to operator
You almost certainly want to use a list:
def parser(lst):
vars = []
for obj in data: # did you mean "for obj in lst:"?
if isinstance(obj,list):
parser(obj)
else:
for string in obj:
vars.append(o) # did you mean "vars.append(string)"?
Then, instead of, say, var5, you would use vars[5].
Doorknob of Snow's answer is correct, but for completeness, you can create a new variable using locals()[var + str(count)] = o. But this is a bad idea, so don't.

Categories

Resources