I will give an example on simple functions:

def first(): a = '1' b = '2' c = '3' print(a,b,c) def second(): lst = [] lst.append(a) lst.append(b) lst.append(c) return lst 

I understand that this code gives an error, so the question is: in what way can I do what I wrote above, or can I not take elements in functions from other functions in python?

If you still can not do this, I would be very happy if you offered some alternative solution.

thank

  • I do not presume to say, but the function environment is removed after execution. Therefore, nothing can be done without passing the parameters. - user207618
  • Issue the code normally. It is not clear what the problem is. I see that this code should work fine. - Mr Fix
  • @MisterFix designed, apparently meant calling first() then calling second() - andreymal
  • @Mrfix, obviously it will not. In second there will be no variables a , b , c , which will throw out an error. - user207618

4 answers 4

Well, if such a thing, then yes. A function does not see what is in another function if it is not nested. That is, it can see variables only in its enclosing region.

 def first(): a = '1' b = '2' c = '3' print(a,b,c) def second(): lst = [] lst.append(a) lst.append(b) lst.append(c) return lst second() 
  • Why then second needed? - user207618
  • This is just an example of how scopes work. You wondered, didn't you? - Mr. Fix
  • I know how it works, but here the function is superfluous. As a demo circuit - go. - user207618
  • Oh, sorry. I am confused with the author :) - Mr. Fix
  • Sorry, but now the problem is that outside the first function I cannot call the second :( Can I fix this somehow ??? - Bernard

You can define a class and add the __call__ method to it __call__

Then an instance of this class can be called as a function, and it will also provide access to its variables.

 class First(object): def __init__(self): self.a = '1' self.b = '2' self.c = '3' def __call__(self): print(self.a, self.b, self.c) first = First() first() # Выведет 1, 2, 3 def second(): lst = [] lst.append(first.a) lst.append(first.b) lst.append(first.c) return lst print(second()) # Выведет ['1', '2', '3'] 
     def first(dt): dt.update(a=1, b=2, c=3) return dt def second(dt): return list(dt.items()) print(second(first({}))) >>> [('a', 1), ('b', 2), ('c', 3)] 
       def first(): global a global b global c a = '1' b = '2' c = '3' print(a,b,c) def second(): lst = [] lst.append(a) lst.append(b) lst.append(c) return lst first() print(second()) 

      declare a, b, c variables global

      • 2
        use of global variables is best avoided. Just return the desired values ​​from first() (use return a, b, c , not print() as in the question) and accept the variables explicitly second(a, b, c) , (instead of using non-local variables as in the question). - jfs