Answer the question
In order to leave comments, you need to log in
Is it possible to pass a variable name to a function?
Hello. Can you tell me if I can change a certain variable in a function? An example is a function:
function sum()
a = 0
b = 0
c = 0
d = 0
i = 0
print(a + b + c + d + i)
sl = {'a': 5, 'c': 2}
sum(sl)
Answer the question
In order to leave comments, you need to log in
Yes, I must have misunderstood the question. I apologize! For my rough example, this solution works!
def set_settings(self, **kwargs):
for name, value in kwargs.items():
getattr(self, name).setText(value)
obj.label1.setText('one')
obj.label2.setText('two')
For example, if I understand you correctly:
>>> def my_func(express, args):
... return eval(express % args)
...
>>> print my_func('%(a)d+%(b)d', {'a': 2, 'b': 3})
5
>>> print my_func('%(c)d*%(d)d', {'c': 4, 'd': 5})
20
>>> def my_sum(myargs):
... my_vars = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'i': 0}
... for im in myargs.keys():
... my_vars[im]=myargs[im]
... return eval('%(a)d+%(b)d+%(c)d+%(d)d+%(i)d' % my_vars)
...
>>> print my_sum({'a': 5, 'c': 2})
7
According to the Python documentation , the locals() dictionary, which is responsible for the values of variables within a function, cannot be implicitly changed.
It is possible, however, to change the values of global variables:
def add(dic):
globals().update(dic)
print(x+y)
add({'x': 2, 'y': 3})
print(x)
print(y)
That's why it is necessary to write it in parentheses. Specify in parentheses the variables separated by commas, which will be defined outside the function, and already inside it perform various operations with them.
For example:
a = 10
e = 40
def function(a, e):
b = 3
c = 11
d = 20
print(a+b+c+d+e)
function(a, e)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question