programing

Python 함수 전역 변수?

copyandpastes 2022. 9. 25. 21:29
반응형

Python 함수 전역 변수?

이와 같이 혼동을 일으켜 글로벌 변수를 사용하는 것은 애당초 피해야 한다는 것을 알고 있습니다만, 이러한 변수를 사용하는 방법은 다음과 같습니다(별도의 함수로 작성된 변수의 글로벌 카피를 호출하려고 합니다).

x = "somevalue"

def func_A ():
   global x
   # Do things to x
   return x

def func_B():
   x = func_A()
   # Do things
   return x

func_A()
func_B()

그럼?x두 번째 함수가 사용하는 것은 글로벌 복사와 동일한 값입니다.x그거func_a사용방법 및 변경방법정의 후 함수를 호출할 때 순서가 중요합니까?

단순히 글로벌 변수에 액세스하려면 해당 이름을 사용합니다.단, 값을 변경하려면 키워드를 사용해야 합니다.

예.

global someVar
someVar = 55

그러면 글로벌 변수 값이 55로 변경됩니다.그렇지 않으면 로컬 변수에 55만 할당됩니다.

함수 정의 목록의 순서는 중요하지 않습니다(서로 참조하지 않는 것으로 가정). 호출된 순서는 중요합니다.

Python 스코프 내에서 아직 선언되지 않은 변수에 대한 할당은 해당 변수가 키워드를 사용하여 글로벌 스코프 변수를 참조한다고 함수의 초기에 선언되지 않는 한 새로운 로컬 변수를 생성합니다.global.

다음으로 의사 코드의 변경된 버전을 보고 어떤 일이 일어나는지 알아보겠습니다.

# Here, we're creating a variable 'x', in the __main__ scope.
x = 'None!'

def func_A():
  # The below declaration lets the function know that we
  #  mean the global 'x' when we refer to that variable, not
  #  any local one

  global x
  x = 'A'
  return x

def func_B():
  # Here, we are somewhat mislead.  We're actually involving two different
  #  variables named 'x'.  One is local to func_B, the other is global.

  # By calling func_A(), we do two things: we're reassigning the value
  #  of the GLOBAL x as part of func_A, and then taking that same value
  #  since it's returned by func_A, and assigning it to a LOCAL variable
  #  named 'x'.     
  x = func_A() # look at this as: x_local = func_A()

  # Here, we're assigning the value of 'B' to the LOCAL x.
  x = 'B' # look at this as: x_local = 'B'

  return x # look at this as: return x_local

사실, 당신은 모든 것을 다시 쓸 수 있습니다.func_B이름이 붙은 변수를 사용하여x_local똑같이 작동하게 될 겁니다

순서는 함수가 전역 x 값을 변경하는 작업을 수행하는 순서에서만 문제가 됩니다.따라서 이 예에서는 순서는 중요하지 않습니다.func_Bfunc_A이 예에서는 순서가 중요합니다.

def a():
  global foo
  foo = 'A'

def b():
  global foo
  foo = 'B'

b()
a()
print foo
# prints 'A' because a() was the last function to modify 'foo'.

주의:global는 글로벌 오브젝트를 변경하는 경우에만 필요합니다.아직 함수 내에서 액세스 할 수 있습니다.global다음과 같은 것이 있습니다.

x = 5

def access_only():
  return x
  # This returns whatever the global value of 'x' is

def modify():
  global x
  x = 'modified'
  return x
  # This function makes the global 'x' equal to 'modified', and then returns that value

def create_locally():
  x = 'local!'
  return x
  # This function creates a new local variable named 'x', and sets it as 'local',
  #  and returns that.  The global 'x' is untouched.

의 차이에 주의해 주세요.create_locally그리고.access_only--access_only콜을 하지 않아도 글로벌x 에 액세스 하고 있습니다.global, 그리고,create_locally사용하지 않다global둘 다 값을 할당하기 때문에 로컬 복사가 생성됩니다.

여기서의 혼란이 글로벌 변수를 사용하면 안 되는 이유입니다.

다른 사람들이 지적했듯이 변수를 선언해야 합니다.global함수의 경우 해당 함수가 전역 변수를 수정할 수 있도록 해야 합니다.액세스만 하고 싶은 경우는, 필요 없습니다.global.

좀 더 자세히 설명하자면, "modify"라는 의미는 다음과 같습니다.글로벌 이름을 재바인드하여 다른 개체를 가리키도록 하려면 이름을 선언해야 합니다.global수에있있 있있있다다

개체를 수정(변환)하는 대부분의 작업은 다른 개체를 가리키도록 글로벌 이름을 다시 바인딩하지 않으므로 이름을 선언하지 않아도 모두 유효합니다.global수에있있 있있있다다

d = {}
l = []
o = type("object", (object,), {})()

def valid():     # these are all valid without declaring any names global!
   d[0] = 1      # changes what's in d, but d still points to the same object
   d[0] += 1     # ditto
   d.clear()     # ditto! d is now empty but it`s still the same object!
   l.append(0)   # l is still the same list but has an additional member
   o.test = 1    # creating new attribute on o, but o is still the same object

함수 내부의 글로벌 변수에 직접 액세스할 수 있습니다.해당 글로벌 변수의 값을 변경하려면 "global variable_name"을 사용합니다.다음의 예를 참조해 주세요.

var = 1
def global_var_change():
      global var
      var = "value changed"
global_var_change() #call the function for changes
print var

일반적으로 이것은 좋은 프로그래밍 연습이 아닙니다.네임스페이스 로직을 깨면 코드를 이해하고 디버깅하기 어려워질 수 있습니다.

다음으로 파라미터의 디폴트값으로 글로벌을 사용한 경우의 예를 제시하겠습니다.

globVar = None    # initialize value of global variable

def func(param = globVar):   # use globVar as default value for param
    print 'param =', param, 'globVar =', globVar  # display values

def test():
    global globVar
    globVar = 42  # change value of global
    func()

test()
=========
output: param = None, globVar = 42

param 값이 42일 것으로 예상했습니다.서프라이즈.Python 2.7은 함수 func를 처음 구문 분석했을 때 globVar의 값을 평가했습니다.globVar 값을 변경해도 param에 할당된 기본값에는 영향을 주지 않습니다.아래와 같이 평가를 연기한 것이, 필요에 따라서 효과가 있었습니다.

def func(param = eval('globVar')):       # this seems to work
    print 'param =', param, 'globVar =', globVar  # display values

아니면, 당신이 원한다면

def func(param = None)):
    if param == None:
        param = globVar
    print 'param =', param, 'globVar =', globVar  # display values

하셔야 합니다.global선언은 글로벌 변수에 할당된 값을 변경할 때 사용합니다.

글로벌 변수에서 읽을 때는 필요하지 않습니다.오브젝트에 메서드를 호출해도(그 오브젝트 내의 데이터가 변경되어도) 오브젝트를 보유하는 변수의 값은 변경되지 않습니다(반사 매직 부재).

언급URL : https://stackoverflow.com/questions/10588317/python-function-global-variables

반응형