How to get/set local variables of a function (from outside) in Python?

前端 未结 5 1356
误落风尘
误落风尘 2020-11-28 10:08

If I have a function (in Python 2.5.2) like:

def sample_func():
    a = 78
    b = range(5)
    #c = a + b[2] - x

My questions are:

5条回答
  •  一生所求
    2020-11-28 10:37

    Not sure if this is what you mean, but as functions are objects in Python you can bind variables to a function object and access them from 'outside':

    def fa():
        print 'x value of fa() when entering fa(): %s' % fa.x
        print 'y value of fb() when entering fa(): %s' % fb.y
        fa.x += fb.y
        print 'x value of fa() after calculation in fa(): %s' % fa.x
        print 'y value of fb() after calculation in fa(): %s' % fb.y
        fa.count +=1
    
    
    def fb():
        print 'y value of fb() when entering fb(): %s' % fb.y
        print 'x value of fa() when entering fa(): %s' % fa.x
        fb.y += fa.x
        print 'y value of fb() after calculation in fb(): %s' % fb.y
        print 'x value of fa() after calculation in fb(): %s' % fa.x
        print 'From fb() is see fa() has been called %s times' % fa.count
    
    
    fa.x,fb.y,fa.count = 1,1,1
    
    for i in range(10):
        fa()
        fb()
    

    Please excuse me if I am terribly wrong... I´m a Python and programming beginner myself...

提交回复
热议问题