开发者

Learning Python: print variable inside a function from another function

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.


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()


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.


Well your func2() is trying to print a variable in the scope of another function. You can either

  • Return the value of var1 when calling func1 (eg. def func2(): print func1() }
  • Call func2 from func1 and pass the value of var1


You could try something like

def func1():
   var1 = "something"
   return var1

def func2():
   print func1()

If you need func1 to do more things than just define var1, then maybe what you need is to define a class and create objects? See http://docs.python.org/tutorial/classes.html


You could try:

filename.py:


def func1():
     var1 = "something"

def func2():
     var = __ import__('filename').var1
     print var
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜