How can I share a variable between functions in Python?

前端 未结 5 781
一个人的身影
一个人的身影 2021-02-13 16:18

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

5条回答
  •  感情败类
    2021-02-13 16:48

    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)
    

提交回复
热议问题