Reputation: 2404
I created a class using a variable that is declared out side the class and then tried to use that class from a different file. But after using in a different file, defining the variable form that file, I get a name not defined error.
Originally fileOne.py
looked like:
dat = 'this string'
class myClass:
def __init__(self):
self.num = 5
def method(self):
return self.num+dat
Now when I change the lay out, so that dat
is defined in the other file that calls myClass.
Changed fileOne.py
#dat = 'this string'
class myClass:
def __init__(self):
self.num = 5
def method(self):
return self.num+dat
fileTwo.py
from fileOne import *
dat = "file 2 str"
obj = myClass()
I get back
NameError: name 'dat' is not defined.
I think what I need to do in replace dat with self.dat and pass it as a function parameter. I'm not sure why I'm having this problem.
Upvotes: 0
Views: 57
Reputation: 260
your class code does not import dat itself. if you want to use configs in different classes, i suggest the following:
class SystemConfig():
dat = 5
class myClass(SystemConfig):
def __init__(self):
self.num = 5
def method(self):
return self.num + SystemConfig.dat
or from a different file:
from fileone import SystemConfig
class myClass(SystemConfig):
def __init__(self):
self.num = 5
def method(self):
return self.num + SystemConfig.dat
this is much better practice , also lets you run system configuration in one place.
Upvotes: 1