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"
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
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.