[英]Global variable functions
I am using a method for storing and recalling global variables in Python.我正在使用一种在 Python 中存储和调用全局变量的方法。 I like it.
我喜欢。 It seems to work for me.
它似乎对我有用。 I am not a coder though.
虽然我不是编码员。 I know nothing about this stuff.
我对这些东西一无所知。 So, wondering where its limitations will be - how and when I will regret using it in future.
所以,想知道它的局限性在哪里 - 我将来会如何以及何时会后悔使用它。
I create a function that will update the value if passed a new one or return the existing value as below:我创建了一个函数,如果传递一个新值或返回现有值,它将更新该值,如下所示:
def global_variable(new_value = None):
# a function that both stores and returns a value
# first deal with a new value if present
if new_value != None
# now limit or manipulate the value if required
# in this case limit to integers from -10 to 10
new_value = min(new_value, 10)
global_variable.value = int(max(new_value, -10))
# now return the currently stored value
try:
# first try and retrieve the stored value
return_value = global_variable.value
except AttributeError:
# and if it read before it is written set to its default
# in this case zero
global_variable.value = 0
return_value = global_variable.value
# either way we have something to return
return return_value
global_variable(3) global_variable(3)
print(global_variable())打印(全局变量())
You can just use global variables.您可以只使用全局变量。 If you need to change them within a function you can use the global keyword:
如果需要在函数内更改它们,可以使用 global 关键字:
s = 1
def set():
global s
s = 2
print(s)
set()
print(s)
> 1
> 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.