A
A
Alexander Rublev2016-05-09 14:49:09
Python
Alexander Rublev, 2016-05-09 14:49:09

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)

Is it possible to somehow change a certain variable in it by passing the name of this variable and the value
? For example:
sl = {'a': 5, 'c': 2}
sum(sl)

And in the end, 7 will be displayed.
I just don’t even know how to implement this!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander Rublev, 2016-05-10
@Meller008

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)

You can call like this:
or like this:
and the following code will be executed:
obj.label1.setText('one')
obj.label2.setText('two')

V
Vladimir Kuts, 2016-05-09
@fox_12

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

well, or if you take your specific example - something like this:
>>> 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

D
DeepBlue, 2016-05-09
@DeepBlue

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)

This code will output the numbers 5, 2 and 3.

E
Error 502, 2016-05-09
@NullByte

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)

also read this article pythonworld.ru/tipy-dannyx-v-python/vse-o-funkciya...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question