1

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

Heatsreef
  • 113
  • 1
  • 1
  • 8

2 Answers2

3

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()
Brad Figueroa
  • 869
  • 6
  • 15
  • `global` is not widely used and it isn't recommended, check [this](https://stackoverflow.com/questions/59330578/how-to-avoid-using-global-variables-in-python) out, but if you don't wanna implement a `class` you can do it. – Brad Figueroa Jul 16 '20 at 04:03
0

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?

DrSpill
  • 552
  • 4
  • 18
  • Aah seems like you already got an answer while I was typing mine. This is still slightly different so will leave it for anyone else! – DrSpill Jul 16 '20 at 04:10