ClaWnN
ClaWnN

Reputation: 49

How to 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()

Upvotes: 2

Views: 628

Answers (3)

Netwave
Netwave

Reputation: 42678

Just return the variable from your first funtion and capture it in the second:

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

a = func1()
func2(a)

Here you have the live example

If what you want is to update a variable within your pyqt app you can use @Devesh answer

Upvotes: 3

Sociopath
Sociopath

Reputation: 13401

Define a outside the function.

a = 5

def func1():
    print(a)

def func2():        
    print(a)

func1()
func2()

Output:

5                                                                                                                                     
5 

Remember

  • not best practice
  • does only work for read access to a

Upvotes: -1

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Just 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

Upvotes: 4

Related Questions