How Can I share common variable between two functions?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • karan991136
    New Member
    • Apr 2019
    • 3

    How Can I share common variable between two functions?

    Can func1 share variable a with func2 without global keyword in python?

    def func1():
    a= 5
    print(a)

    def func2():
    print(a)

    func1()
    func2()
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    For the code posted above, the variable, a, is local to/only exists in func1. You have to return it for it to exist outside the function. Every tutorial covers this. Tutorials are write once, read many, so we don't have to answer the same questions over and over and over. Start with this part of a the tutorials point tutorial http://www.tutorialspoint.com/python..._functions.htm

    Comment

    • aakashdata
      New Member
      • Apr 2019
      • 7

      #3
      You can define both functions in a class, and make a as an attribute.

      class A:
      def __init__(self, a):
      self.a = a
      def func1(self):
      self.a= 5
      print(self.a)
      def func2(self):
      print(self.a)
      obj = A(4)
      obj.func2()
      obj.func1()


      The output will be.

      4
      5

      Comment

      Working...