Scope Basics
17 May 2018Tripped on this today. Let’s talk about scope! Python organizes scope as LEGB: Local, Enclosing, Global, Built-in.
On to the example. This code doesn’t work:
class Structure:
structureName = None
structureDescription = None
def info(self):
print("######## " + structureName + " #########")
print(structureDescription)
greatHall = Structure() greatHall.info()
The scope of info() includes structureName in the method, but does NOT include structureName at the enclosing level. So, it’s out of scope. This is fixed by indicating where structureName actually is:
def info(self):
print("######## " + self.structureName + " #########")
print(self.structureDescription)
I initially thought this error had to do with a subclass, but including the self arguement in Structure.info() makes this work as well:
class Town_hall(Structure):
structureName = "Town Hall"
structureDescription = "Spawn workers from here!"
greatHall = Town_hall() greatHall.info()