全局变量功能

时间:2019-05-02 16:57:16

标签: python global

我正在使用一种在Python中存储和调用全局变量的方法。我喜欢。它似乎为我工作。我不是编码员。我对这个东西一无所知。因此,想知道它的局限性在哪里-我将来如何以及何时会后悔。

我创建了一个函数,该函数将在传递新值时更新该值,或者返回如下所示的现有值:

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)

这样检索

print(global_variable())

1 个答案:

答案 0 :(得分:2)

您可以只使用全局变量。如果需要在函数中更改它们,可以使用global关键字:

s = 1
def set():
    global s
    s = 2
print(s)
set()
print(s)

> 1
> 2