简体   繁体   English

如何在 Python 中的函数之间共享变量?

[英]How can I share a variable between functions in Python?

I have two functions, fun1 and fun2 , which take as inputs a string and a number, respectively.我有两个函数fun1fun2 ,它们分别将字符串和数字作为输入。 They also both get the same variable, a , as input.它们也都获得相同的变量a作为输入。 This is the code:这是代码:

a = ['A','X','R','N','L']

def fun1(string,vect):
    out = []
    for letter in vect:
        out. append(string+letter)
    return out

def fun2(number,vect):
    out = []
    for letter in vect:
        out.append(str(number)+letter)
    return out

x = fun1('Hello ',a)
y = fun2(2,a)

The functions perform some nonsense operations.这些函数执行一些无意义的操作。 My goal would be to rewrite the code in such a way that the variable a is shared between the functions, so that they do not take it as input anymore.我的目标是以变量a在函数之间共享的方式重写代码,以便它们不再将其作为输入。

One way to remove variable a as input would be by defining it within the functions themselves, but unfortunately that is not very elegant.删除变量a作为输入的一种方法是在函数本身中定义它,但不幸的是,这不是很优雅。 What is a possible way to reach my goal?实现我的目标的可能方法是什么?

The functions should operate in the same way, but the input arguments should only be the string and the number ( fun1(string) , fun2(number) ).这些函数应该以相同的方式运行,但输入 arguments 应该只是字符串和数字( fun1(string)fun2(number) )。

Object-oriented programming helps here:面向对象的编程在这里有帮助:

class MyClass(object):
    def __init__(self):
        self.a = ['A','X','R','N','L']  # Shared instance member :D

    def fun1(self, string):
        out = []
        for letter in self.a:
            out.append(string+letter)
        return out

    def fun2(self, number):
        out = []
        for letter in self.a:
            out.append(str(number)+letter)
        return out

a = MyClass()
x = a.fun1('Hello ')
y = a.fun2(2)

An alternative to using classes: You can use the global keyword to use variables that lie outside the function.使用类的替代方法:您可以使用global关键字来使用位于函数之外的变量。

a = 5
def func():
    global a
    return a+1

print (func())

This will print 6.这将打印 6。

But global variables should be avoided as much as possible.但应尽可能避免使用全局变量。

Since a<\/code> is defined outside the function scope and before<\/strong> the functions are defined, you do not need to feed it as an argument.由于a<\/code>是在函数范围之外并且在定义函数之前<\/strong>定义的,因此您不需要将其作为参数提供。 You can simply use a<\/code> .您可以简单地a<\/code> .

Python will first look whether the variable is defined in the function scope, and if not, it looks outside that scope. Python 将首先查看变量是否在函数范围内定义,如果没有,则在该范围之外查找。

a = ['A','X','R','N','L']

def fun1(string):
    out = []
    for letter in a:
        out.append(string+letter)
    return out

def fun2(number):
    out = []
    for letter in a:
        out.append(str(number)+letter)
    return out

x = fun1('Hello ')
y = fun2(2)

This can be easily achieved using the global<\/code> keyword.这可以使用global<\/code>关键字轻松实现。 That makes the a<\/code> variable available in the whole file.这使得a<\/code>变量在整个文件中可用。 However, the global variables should be avoided as much, because every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.但是,应该尽可能避免使用全局变量,因为每个函数都可以访问这些变量,因此越来越难以确定哪些函数实际读取和写入这些变量。

a = ['A','X','R','N','L']

def fun1(string):
    out = []
    for letter in a:
        out. append(string+letter)
    return out

def fun2(number):
    out = []
    for letter in a:
        out.append(str(number)+letter)
    return out

x = fun1('Hello ')
y = fun2(2,a)

Object Oriented Programming<\/a> and making a<\/code> a member variable is absolutely the best solution here. 面向对象编程<\/a>和制作a<\/code>变量绝对是这里最好的解决方案。

But sometimes you have codes that are not OO, think of a flask application for example when you have multiple endpoints that you'd like to share some value.但是有时您的代码不是面向对象的,例如,当您有多个想要共享某些价值的端点时,请考虑一个烧瓶应用程序。 In this case, a shared or global variable is the way to go.在这种情况下,共享或全局变量是可行的方法。 Meaning defining the varibale outside the scope of all the methods so it could be accessed anywhere.意味着在所有方法的范围之外定义变量,以便可以在任何地方访问它。

Now, if the value of your variable never changes, you sould use uppercase letters for naming, to mark it as final and in a sense global (similar to final static variables in Java).现在,如果你的变量的值永远不会改变,你应该使用大写字母来命名,将其标记为 final 并且在某种意义上是全局的(类似于 Java 中的 final 静态变量)。

A = ['A','X','R','N','L']<\/code>

But if the value does change, first, the name should be lowercase a = ['A','X','R','N','L']<\/code> .但是如果值确实发生了变化,首先,名称应该是小写a = ['A','X','R','N','L']<\/code> 。 Second, you'd want to limit the places where the value can change, ideally to only one method, and there you can use the global<\/code> keyword to change the value其次,您希望限制值可以更改的地方,理想情况下只有一种方法,并且您可以使用global<\/code>关键字来更改值

a = ['A','X','R','N','L']

def fun1(string,vect):
    global a
    a.append('W')

    out = []
    for letter in vect:
        out. append(string+letter)
    return out

def fun2(number,vect):
    out = []
    for letter in vect:
        out.append(str(number)+letter)
    return out

x = fun1('Hello ',a)
y = fun2(2,a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM