如何在 Python 中的函数之间共享变量? [英] How can I share a variable between functions in Python?

查看:23
本文介绍了如何在 Python 中的函数之间共享变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数,fun1fun2,它们分别接受一个字符串和一个数字作为输入.它们也都获得相同的变量 a 作为输入.这是代码:

I have two functions, fun1 and fun2, which take as inputs a string and a number, respectively. They also both get the same variable, a, as input. 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)

函数执行一些无意义的操作.我的目标是以变量 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. What is a possible way to reach my goal?

函数应该以相同的方式运行,但输入参数应该只是字符串和数字(​​fun1(string), fun2(number)).

The functions should operate in the same way, but the input arguments should only be the string and the number (fun1(string), fun2(number)).

推荐答案

面向对象编程在这里有帮助:

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)

这篇关于如何在 Python 中的函数之间共享变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆