【问题标题】:can we create a variable that can be modified from any functions in python?我们可以创建一个可以从 python 中的任何函数修改的变量吗?
【发布时间】:2020-06-25 17:37:58
【问题描述】:

您好想知道是否有一种方法可以声明一个可以从任何函数修改而不必使用 global 关键字的变量,因为我有很多函数修改某个变量,而且有一半的时间我忘了放global myvar 创建修改 myvar 的新函数时。

【问题讨论】:

  • 你描述的是一个全局变量。

标签: python function variables global


【解决方案1】:

是的,这是 python 的默认行为。但是,您必须注意一些细微差别:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

global_var1 = {}
global_var2 = 10
global_var3 = []


def manipulate_globals1():
    # this is the behavior you want
    global_var1['new_entry'] = 10
    global_var3.append(10)

    # this would fail
    # global_var2 += 10

    # but this works
    global global_var2
    global_var2 += 10


def manipulate_globals2():
    # here we create scoped variables with the same name as the globals
    global_var1 = []
    global_var2 = 5


if __name__ == '__main__':
    print(global_var1, global_var2, global_var3)
    manipulate_globals1()
    print(global_var1, global_var2, global_var3)
    manipulate_globals2()
    print(global_var1, global_var2, global_var3)

当你想在函数中操作非容器变量时,你可以这样做:

创建一个包含内容的文件 globals.py:

a = 10
b = 20

在您的主/核心文件中:

import globals

def manipulate_globals():
    globals.a = 20 
    globals.b = 30

if __name__ == '__main__':
    manipulate_globals()
    print(globals.a, globals.b)

虽然这是一种不好的做法,但您不应该使用全局通胀

【讨论】:

    【解决方案2】:

    您可以使用classes。创建新对象时,您可以初始化变量并在该对象的任何方法中使用它们。

    这些变量有self. 前缀。

    【讨论】:

    • 是的,但是对于类,我不能在类外使用类的变量
    • @rémicouturier:你不能?为什么不呢?
    • 哦,是的,你是对的,它有效(而且它也适用于字典)
    【解决方案3】:

    是的,可以在没有关键字 global 的情况下声明全局变量。变量的范围取决于它在代码中的声明位置。要声明一个新的全局变量,只需在所有其他函数的范围之外声明它 有关 python 中的作用域以及全局和局部变量的更多帮助,请查看https://www.geeksforgeeks.org/global-local-variables-python/

    【讨论】:

    • 是的,但据我所知,如果我在函数之外声明一个变量,我可以从函数中访问它的值,但我不能修改它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多