Reputation: 1
I have problems with the following code, it says "NameError: global name 'Teater' is not defined" I can not solve it by myself...
teaterLista = []
lista = []
class Teater:
def __init__(self, teaterNamn, plats, pensionar,vuxen,barn):
self.teaterNamn = teaterNamn
self.plats = plats
self.pensionar = pensionar
self.vuxen = vuxen
self.barn = barn
def readData():
#x = Teater(x,teaterNamn, plats,pensionar,vuxen,barn)
dataFile = open('c:/Teater.txt','r')
for line in dataFile:
if(line != '\n'):
temp = line.split('=',1)[1]
lista.append(temp.strip()) #strip tar bort radavslut
x = Teater(x,lista[0],lista[1],lista[2],lista[3],lista[4])
#teaterLista[0] = x
#print(teaterLista[0])
readData()
Upvotes: 0
Views: 3088
Reputation: 12263
You call readData()
during class definition. In Python a class body is executed during its definition in the contex of the class definition just as normal code would be. As the class is not completely defined at that moment, you cannot create a new instance, yet, thus get the error.
Dedent the whole definition for readData
and the following line so all this is executed after the definition of the class has completed. This makes readLine
a module-level function, not a class method. This is typical for a factory function.
teaterLista = []
lista = []
class Teater:
def __init__(self, teaterNamn, plats, pensionar,vuxen,barn):
self.teaterNamn = teaterNamn
self.plats = plats
self.pensionar = pensionar
self.vuxen = vuxen
self.barn = barn
def readData():
#x = Teater(x,teaterNamn, plats,pensionar,vuxen,barn)
dataFile = open('c:/Teater.txt','r')
for line in dataFile:
if(line != '\n'):
temp = line.split('=',1)[1]
lista.append(temp.strip()) #strip tar bort radavslut
x = Teater(lista[0],lista[1],lista[2],lista[3],lista[4])
#teaterLista[0] = x
#print(teaterLista[0])
readData()
Note: x = Teater(x, ...
will not work, as x
is not defined for the first invocation. If you think about specifying this for the self
argument: no need; this is done implicitly. You should read how classes work in the documentation/tutorial.
You have to be careful in Python to correctly indent your code, as that defines the block scope.
Upvotes: 1