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

前端 未结 5 1355
误落风尘
误落风尘 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:42

    I'm not sure what your use-case is, but this may work better as a class. You can define the __call__ method to make a class behave like a function.

    e.g.:

    >>> class sample_func(object):
    ...     def __init__(self):
    ...         self.a = 78
    ...         self.b = range(5)
    ...     def __call__(self):
    ...         print self.a, self.b, self.x
    ... 
    >>> f = sample_func()
    >>> print f.a
    78
    >>> f.x = 3
    >>> f()
    78 [0, 1, 2, 3, 4] 3
    

    (this is based on your toy example, so the code doesn't make much sense. If you give more details, we may be able to provide better advice)

提交回复
热议问题