Hướng dẫn python overwrite global variable in function - python ghi đè biến toàn cục trong hàm

Trong phạm vi Python, bất kỳ gán nào cho một biến chưa được khai báo trong phạm vi đó đều tạo ra một biến cục bộ mới trừ khi biến đó được khai báo sớm hơn trong hàm đề cập đến biến phạm vi toàn cầu với từ khó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'.
6.

Chúng ta hãy xem một phiên bản đã sửa đổi của mã giả của bạn để xem điều gì sẽ xảy ra:

# 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

Trên thực tế, bạn có thể viết lại tất cả

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'.
7 với biến có tên
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'.
8 và nó sẽ hoạt động giống hệt nhau.

Thứ tự chỉ quan trọng theo thứ tự mà các chức năng của bạn thực hiện các hoạt động thay đổi giá trị của x toàn cầu. Do đó, trong ví dụ của chúng tôi, trật tự không quan trọng, vì

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'.
7 gọi
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.
0. Trong ví dụ này, trật tự không quan trọng:

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'.

Lưu ý rằng

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'.
6 chỉ được yêu cầu để sửa đổi các đối tượng toàn cầu. Bạn vẫn có thể truy cập chúng từ trong một chức năng mà không cần khai báo
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'.
6. Vì vậy, chúng tôi có:

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.

Lưu ý sự khác biệt giữa

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.
3 và
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.
4 -
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.
4 đang truy cập vào toàn cầu X mặc dù không gọi
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'.
6 và mặc dù
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.
3 cũng không sử dụng
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'.
6, nhưng nó tạo ra một bản sao cục bộ vì nó gán giá trị.

Sự nhầm lẫn ở đây là lý do tại sao bạn không nên sử dụng các biến toàn cầu.

Các biến toàn cầu và cục bộ cùng tên

Kiểm tra ví dụ này,

Quảng cáo

total = 100 

def func1(): 
   total = 15 

print('Total = ', total) 

func1() 

print('Total = ', total)
Output:
Total = 100 
Total = 100

Ở đây 'Tổng số' là một biến toàn cầu và hàm func () có một biến cục bộ cùng tên. Theo mặc định, một hàm ưu tiên cho biến cục bộ hơn biến toàn cầu nếu cả hai đều có cùng tên. Do đó, trong mã trên khi chúng tôi sửa đổi biến 'tổng' bên trong hàm thì nó không được phản ánh bên ngoài hàm. Bởi vì bên trong hàm func () Tổng biến được coi là biến cục bộ.total' is a global variable and func() function has a local variable with same name. By default a function gives preference to
local variable over global variable if both are of same name. Therefore in above code when we modified 'total' variable inside the function then it was not reflected outside the function. Because inside function func() total variable is treated as local variable.

Nhưng điều gì sẽ xảy ra nếu muốn truy cập biến toàn cầu bên trong một hàm có biến cục bộ cùng tên?

Sử dụng từ khóa toàn cầu † để sửa đổi biến toàn cầu bên trong một chức năng

Nếu chức năng của bạn có một biến cục bộ có cùng tên với biến toàn cầu và bạn muốn sửa đổi chức năng biến toàn cầu bên trong thì hãy sử dụng từ khóa 'toàn cầu' trước tên biến khi bắt đầu chức năng, tức là.

global total

Nó sẽ làm cho chức năng tham khảo tổng số biến toàn cầu bất cứ khi nào được truy cập. Kiểm tra ví dụ này,

total = 100
def func():
    # refer to global variable 'total' inside function
    global total
    if total > 10:
        total = 15

print('Total = ', total)
func()
print('Total = ', total)

Output:

Total =  100
Total =  15

Như bạn có thể thấy sửa đổi được thực hiện cho tổng số biến toàn cầu hiện có thể nhìn thấy bên ngoài chức năng.

Khi chúng tôi sử dụng từ khóa toàn cầu với một biến bên trong hàm thì biến cục bộ sẽ được ẩn. Nhưng điều gì sẽ xảy ra nếu chúng ta muốn giữ Bot là biến cục bộ & toàn cầu với giống nhau và sửa đổi cả hai trong chức năng? Hãy xem làm thế nào để làm điều đó,

Sử dụng Globals () để truy cập các biến toàn cầu bên trong hàm

Vì các từ khóa 'toàn cầu' ẩn biến cục bộ có cùng tên, vì vậy để truy cập cả biến cục bộ và toàn cầu bên trong một hàm, có một cách khác, tức là toàn cầu () Sử dụng nó để truy cập / sửa đổi biến toàn cầu mà không cần sử dụng từ khóa 'toàn cầu' I, e.'global' keywords hide the local variable with same name, so to access both the local & global variable inside a function there is an another way i.e. global() function.
globals() returns a dictionary of elements in current module and we can use it to access / modify the global variable without using 'global' keyword i,e.

total = 100

def func3():
    listOfGlobals = globals()
    listOfGlobals['total'] = 15
    total = 22
    print('Local Total = ', total)

print('Total = ', total)
func3()
print('Total = ', total)

Đầu ra:

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'.
0

Như bạn có thể thấy rằng chúng tôi có biến cục bộ và biến toàn cầu với cùng tên, tức là tổng số và chúng tôi đã sửa đổi cả hai bên trong hàm. Bằng cách sử dụng từ điển được trả về bởi Globals () để tham khảo biến toàn cầu thay vì từ khóa 'toàn cầu'. Nó sẽ không ẩn biến cục bộ bên trong hàm.globals() to refer global variable instead of keyword 'global'. It will not hide local variable inside the function.

Xử lý lỗi không liên lạc

Nếu chúng ta cố gắng truy cập một biến toàn cầu với từ khóa 'toàn cầu' hoặc toàn cầu () bên trong một hàm, tức là.

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'.
1

Nó sẽ ném một lỗi như thế này,

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'.
2

Để ngăn chặn lỗi này, chúng tôi cần sử dụng từ khóa 'toàn cầu' hoặc hàm toàn cầu (), tức là.

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'.
3

Ví dụ hoàn chỉnh về biến toàn cầu và toàn cầu () trong Python

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'.
4

Output:

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'.
5

Tôi có thể thay đổi một biến toàn cầu trong chức năng Python không?

Một biến cục bộ là một biến được xác định trong một hàm.Các biến như vậy được cho là có 'phạm vi' cục bộ.Các chức năng có thể truy cập các biến toàn cầu và sửa đổi chúng.Functions can access global variables and modify them.

Bạn có thể thay đổi một biến toàn cầu trong một hàm không?

Với cửa sổ ['variablename'] hoặc cửa sổ.VariaBlename Bạn có thể sửa đổi giá trị của biến toàn cầu bên trong một hàm.

Các biến toàn cầu có thể được ghi đè không?

Chúng tôi biết rằng chúng tôi có thể ghi đè giá trị của các biến cục bộ bất kỳ số lần nào trong một chương trình.Tương tự, chúng ta cũng có thể ghi đè giá trị của các biến toàn cầu trong một hàm.we can also overwrite the value of global variables in a function.

Một hàm có thể sửa đổi một biến trong Python?

Vâng, một hàm không bao giờ có thể sửa đổi một biến bất biến bên ngoài phạm vi cục bộ của nó, 00:34 và một hàm có thể sửa đổi một biến có thể thay đổi bên ngoài phạm vi cục bộ của nó.a function can never modify an immutable variable outside its local scope, 00:34 and a function is able to modify a mutable variable outside its local scope in place.