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

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

    Expecting a variable in a function to be set by an outside function BEFORE that function is called is such bad design that the only real answer I can recommend is changing the design. A function that expects its internal variables to be set before it is run is useless.

    So the real question you have to ask is why does that function expect x to be defined outside the function? Does the original program that function use to belong to set a global variable that function would have had access to? If so, then it might be as easy as suggesting to the original authors of that function that they instead allow x to be passed in as an argument. A simple change in your sample function would make the code work in both situations:

    def sample_func(x_local=None):
      if not x_local:
        x_local = x
      a = 78
      b = range(5)
      c = a + b[2] - x_local
    

    This will allow the function to accept a parameter from your main function the way you want to use it, but it will not break the other program as it will still use the globally defined x if the function is not given any arguments.

提交回复
热议问题