Why can I use the instance of a class in the following function without using globals?
class TestClass:
def __init__(self, name):
self.name = name
def MyName(self):
print "My name is: " + self.name
def testFunc():
# why can I use the instance here?
print "in testFunc()"
instance.MyName()
if __name__ == '__main__':
instance = TestClass("abc")
print "in __main__"
instance.MyName()
testFunc()
In Python, globals are reachable by name from any scope. Your test_func()
function can reference instance
by name since it has been bound in global scope, namely in the if __name__ == '__main__'
block.
The global
keyword is useful for when you want to bind a global name from a local scope. To do so, you declare global foo
and then bind it, e.g. foo = 1
, from within the local scope.
Summarized: When referencing a global variable by name global
is not required. When binding a global variable, global
is required.