Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning Python: print variable inside a function from another function

Tags:

python

I want to do the following in python:

def func1():
 var1 = "something"

def func2():
 print var1

What is the correct mode to do this ? I've not found in documentation at all

PS. If possible, it's not my plan to make that 'var1' a global variable.

Thanks.

like image 533
Simão Avatar asked Sep 08 '25 12:09

Simão


2 Answers

I assume you don't want to pass the variable as a parameter between the function calls. The normal way to share state between functions would be to define a class. It may be overkill for your particular problem, but it lets you have shared state and keep it under control:

class C:
    def func1(self):
     self.var1 = "something"

    def func2(self):
     print self.var1

foo = C()
foo.func1()
foo.func2()
like image 171
Duncan Avatar answered Sep 10 '25 04:09

Duncan


No, it is not possible to do things like that. This is because of something called "scope". You can either create a module-level variable or place it in an OOP construct.

like image 21
cwallenpoole Avatar answered Sep 10 '25 04:09

cwallenpoole