Ben Grant Ben Grant - 1 month ago 10
Python Question

Why can't I reference the instance/object outside the function I created it in?

Why can't I reference the instance/object outside the function I created it in and how can I fix this.

Simplified Code:

class MyClass:

def PrintThis(self):
print ("Hello World")



def MyClassPrinter():
x = MyClass()

x.PrintThis() #This Works





MyClassPrinter()

x.PrintThis() #This "is not defined"


This comes out as:

Hello World
Traceback (most recent call last):
File "C:\User\Desktop\test.py", line 19, in <module>
x.PrintThis() #This "is not defined"
NameError: name 'x' is not defined


I can't remove the function or initialize it outside the function because in the original code it actually does something.

I apologise if this is a stupid question or already answered somewhere else.

Answer

After the function is executed and returned its local variables aren't available for referencing any more. They are bound in the scope of the function (locally) and are not accessible outside of it.

One option is returning the created instance and binding it to a name in the global scope; this requires two changes: a return x in the function MyClassPrinter and an x = MyClassPrinter() assignment to bind the returned value of the function to the name x outside:

def MyClassPrinter():
    x = MyClass()
    x.PrintThis() #This Works
    return x

x = MyClassPrinter()
x.PrintThis()

Another option is to bind the object in the global scope by using the global statement:

def MyClassPrinter():
    global x 
    x = MyClass()
    x.PrintThis() #This Works

global takes care to bind x to the global and not local scope thereby allowing it to be referenced when outside the function.