Reputation: 119
So, I am writing a neural network and it works flawless. But I have decided to make a GUI with tkinter for easy control. My problem is that I can create an instance of the AI in one function, but can not access it form another function in the same hierarchy(no function is in any class). Nn is another python script
def ph1():
n = Nn.neuralNetwork(v, v, v, v)
def ph2():
n.something()
Error code I'm getting:
name 'n' is not defined
Upvotes: 1
Views: 88
Reputation: 572
It seems like n is a locally created object within the function ph1. If you would like to access it from ph2 you will need to either call the function inside ph2 and return n or have both the functions in a class with n being an instance variable.
The simpler of the two is as follows:
def ph1():
n = Nn.neuralNetwork(v, v, v, v)
return n
def ph2():
n = ph1()
n.something()
Is this something you can consider for your code?
Upvotes: 0
Reputation: 875
The error you're getting is because n
just exits in the local namespace
of ph1()
function and ph2()
can't call it because concept of variable scope
. So you have the following options to do it without error:
Using as parameter
def ph1():
n = Nn.neuralNetwork(v, v, v, v)
return n
def ph2(n):
n.something()
n = ph1()
ph2(n)
Using a class
:
class Ph:
def __init__(self):
self.n = None
def ph1():
self.n = Nn.neuralNetwork(v, v, v, v)
def ph2():
self.n.something()
Using global
variable:
n = None
def ph1():
global n
n = Nn.neuralNetwork(v, v, v, v)
def ph2():
global n
n.something()
Upvotes: 3