Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

python - Is it possible to access a local variable in another function?

Goal: Need to use local variable in another function. Is that possible in Python?

I would like to use the local variable in some other function. Because in my case I need to use a counter to see the number of connections happening and number of connections releasing/ For that I am maintaining a counter. To implement that I have written sample code for count and returning local variable in another function.

How can I print t & my_reply in the test() function?

Code: counter_glob.py

my_test = 0
t = 0

def test():
    print("I: ",t)
    print("IIIIIIII: ",my_reply)

def my():
    global t
    reply = foo()
    t = reply
    print("reply:",reply)
    print("ttttt:",t)

def foo():
    global my_test
    my_test1 = 0
    my_test += 1
    print my_test1
    my_test1 = my_test
    my_test += 1
    print("my_test:",my_test1)
    return my_test1

my()

Result:

> $ python counter_glob.py
 0
 ('my_test:', 1)
 ('reply:', 1)
 ('ttttt:', 1)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are different ways to access the local scope of a function. You can return the whole local scope if you want by calling locals() this will give you the entire local scope of a function, it's atypical to save the local scope. For your functions you can save the variables that you need in the function itself, func.var = value:

def test():
    print("I: ", my.t)
    print("IIIIIIII: ", my.reply)

def my():
    my.reply = foo() 
    my.t = m.reply
    print("reply:", my.reply)
    print("ttttt:", my.t)

You can now access t and reply normally. Each time you call your function my and reply will be updated, whatever foo returns will be assigned to my.reply.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...