I created a variable conID
in one function and I want to use it in another. Both functions are inside a class.
The problem is that in the second function the first function is called, so self.reqSecDefOptParams
calls the first function. And after that conID
receives it value. If I try to output condID
in the second function I can't, it says its value is still None
. Is there a way to first call the first function and then output the value in the same function?
The first function:
def contractDetails(self, reqId: int, contractDetails: ContractDetails):
string = str((contractDetails))
letter_list = string.split(",")
print(letter_list)
conID = letter_list[90] # the variable I need
The second function:
def start(self):
# using the variable again
self.reqSecDefOptParams(1, contract.symbol, "", "STK", conID)
CodePudding user response:
Welcome @LaForge1071! You have a few ways you can do this! One way you might do this is by passing the variable to the new function like this
def func_a():
foo = 'bar'
func_b(foo)
def func_b(var):
print(var)
func_a()
or, and I don't recommend this, you can use global scope to solve this like so,
def func_a():
global foo
foo = 'bar'
func_b()
def func_b():
print(foo)
func_a()
CodePudding user response:
You said both function are in one class, so maybe declare the variable to be a class variable:
class A:
def __init__(self):
self.foo = None
def func_a(self):
self.foo = "Hello"
def func_b(self):
if self.foo is not None:
print(self.foo)
CodePudding user response:
you can declare this variable in init funciton ,just like constrution function in c/c .
def __init__(self):
self.foo = init_value