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
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)
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
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