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
5 Answers 5
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
Comments
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)
3 Comments
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
Comments
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
Comments
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
ob=A(),print(ob.aFunction())?? Addreturn aVariableinside the function