Ravi Coder
Ravi Coder

Reputation: 23

variable inside of function how to use that variable outside of function in python

How to use variable outside of function which is define inside of function? And Function should declare in class.

class A:
  def aFunction(self):
    aVariable = "Hello"

Now here I want to use that aVariable

Upvotes: 0

Views: 1673

Answers (5)

user15801675
user15801675

Reputation:

The return keyword will return the value provided. Here, you have provided self.aVariable. Then, you can assign the value to a variable outside the class and print the variable.

class A:

    def aFunction(self):
        self.aVariable = "Hello"
        return self.aVariable

a = A() #==== Instantiate the class
f=a.aFunction() #==== Call the function. 
print(f)

This will print: Hello

Upvotes: 1

Paras Gupta
Paras Gupta

Reputation: 294

There are several methods you can try.

class A:
    def aFunction(self):
        self.aVariable = "Hello"
    # you can access self.aVariable in the class
class A:
    def aFunction(self):
        aVariable = "Hello"
        return aVariable
    # use self.aFunction() whenever you need this variable

Upvotes: 1

Buddy Bob
Buddy Bob

Reputation: 5889

There are definitely more options that maybe others will provide, but these are the options I have come up with.

Use return

class A: 
    def aFunction(self): 
        aVariable = "Hello"
        return aVariable
obj = A()
var = obj.aFunction()
print(var)

use global

class A: 
    def aFunction(self): 
        global aVariable
        aVariable = "Hello"
obj = A()
obj.aFunction()
print(aVariable)

You can use self to your advantage

class A: 
    def __init__(self):
        self.aVariable = None
    def aFunction(self): 
        self.aVariable = "Hello"
obj = A()
obj.aFunction()
print(obj.aVariable)

Upvotes: 1

Connor
Connor

Reputation: 297

To use a variable from a class outside of the function or entire class:

class A:

    def aFunction(self):
        self.aVariable = 1

    def anotherFunction(self):
        self.aVariable += 1

a = A()  # create instance of the class
a.aFunction()  # run the method aFunction to create the variable
print(a.aVariable)  # print the variable
a.anotherFunction()  # change the variable with anotherFunction
print(a.aVariable)  # print the new value 

Upvotes: 1

Theo Godard
Theo Godard

Reputation: 368

If you want to use this variable within the class A, how about using an instance variable?

class A: 
    def aFunction(self): 
        self.aVariable = "Hello"

Now you can use self.aVariable in another function of the same class

Upvotes: 2

Related Questions