Hello. Tell me, can I 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 of Example:

 sl = {'a': 5, 'c': 2} sum(sl) 

And in the end, 7 will be displayed. I just can't even imagine how this can be realized!

  • You can write a function that changes the bytecode of a function, but this is hardly what you need. In general, you are doing something wrong. - Vadim Shender
  • I guess I made a bad example! What I really want to try! Although I doubt that I can clearly explain. I have such a window written in Qt joxi.ru/v29lRansGKG7Dm.jpg As you can see at the moment this window is written to add fabric! If I use this window to add buttons, then I need to change the captions (fabric for buttons, weight per count, etc.) if I edit the record, then I need to insert the values ​​into LineEdit. I wanted to write a function to which I will pass the name of the widget, and the value to be inserted. - Alexander Rublev
  • Well, make this name and value parameters. Or pack in one variable, like {'popup_title': u'Добавление пуговицы', 'fields': [{'title': u'Пуговица', 'type': ButtonSelector},...]} . - Lebedev Ilya
  • I want to do something like this! But I do not know how to apply these changes in the function itself! - Alexander Rublev
  • Very rude example joxi.ru/12MjgENf4dMMpA.jpg - Alexander Rublev

4 answers 4

If I, having read everything, correctly understood what you need, then it is done like this:

 def sum(values=None): if values is None: values = {} a = values.get('a', 0) b = values.get('b', 0) c = values.get('c', 0) d = values.get('d', 0) i = values.get('i', 0) return a + b + c + d + i 

If you take your rough example from a comment, which, I think, probably closer to your task, I would do this:

 def set_settings(self, **kwargs): for name, value in kwargs.items(): getattr(self, name).setText(value) 

It will be possible to call:

 obj.set_settings(label1='one', label2='two') 

or so:

 obj.set_settings(**{'label1': 'one', 'label2': 'two'}) 

and the following code will be executed:

 obj.label1.setText('one') obj.label2.setText('two') 
  • getattr (self, name) .setText (value) That's what I needed !!! Thank! But really there is nothing similar for my original example? - Alexander Rublev
  • @Alexander Rublev, if you use Python2, you can use exec . If you have the 3rd version, then there is no easy way (to dynamically modify local variables). Although it is possible to use a dictionary instead of variables, then everything is simple. - Vadim Shender
  • Dictionary do you mean {} this? But in my case it would not help! - Alexander Rublev
  • @Alexander Rublev, look, it’s just impossible to solve the problem (you cannot change the local variables of functions dynamically, and you don’t need to). Therefore, you have two options: either you need to rethink the task (this is the most correct option, because what you want is very strange and almost certainly not needed), or to make a decision possible, and the easiest way instead of local variables store the values ​​you need in the dictionary, and change it in the way shown by me in the answer, just instead of the variable a , you will now have access to the dictionary: d['a'] . - Vadim Shender
  • Thank! I understood you! You just helped a lot! - Alexander Rublev

If you need to implement exactly the type example

 sl = {'a': 5, 'c': 2} _sum(sl) 

which will output 7, you can do this:

 def _sum(s): print(sum(s.values())) 

The values method of the dict object lists values ​​in a dictionary.

You can implement differently:

 def _sum(**kwargs): print('kwargs:', kwargs) print(sum(kwargs.values())) 

Then when you call

 _sum(a=1, b=2, c=3) 

will be displayed

 kwargs: {'c': 3, 'b': 2, 'a': 1} 6 

( kwargs output added to show what kwargs into it)

Also, a dictionary can be passed to this function as an argument, only when calling you need to add two asterisks before it:

 >>> s1 = {'a': 5, 'c': 2} >>> _sum(**s1) kwargs: {'c': 2, 'a': 5} 7 

More about function arguments

    It is possible so:

     def _sum(a=0, b=0, c=0, d=0, i=0): return a + b + c + d + i 

    Then you can call:

     print _sum(a=5, b=2) 

    or so:

     kwargs = {'a': 4, 'b': 2} print _sum(**kwargs) # всё внимание на звёздочки 

    And you can pack all the parameters in one dictionary:

     def _sum(params): return params['a'] + params['b'] * params['mult'] 

    then you need to call like this:

     _sum({'a': 5, 'b': 2, 'mult': 3}) 
    • Yes you can, BUT! if we have such variables not 5 and 15? - Alexander Rublev
    • If there are 15 such variables, then it is necessary to split it into several functions. - Lebedev Ilya

    If the function itself you can not change, then I think it can not be done so. And if you can change, you should enter the argument. It can be made compound like yours. Then the function can use it as you like, incl. replacing some of its variables with the value of that argument.

    In general, without changing this function, you cannot pass the name of this variable.