Python 3.x 在类方法内导入会产生NameError
我尝试从类函数中的文件导入函数。 无论我如何改变它,当我尝试加载函数时,它都会导致一个NameError 模块代码结构为:Python 3.x 在类方法内导入会产生NameError,python-3.x,python-import,Python 3.x,Python Import,我尝试从类函数中的文件导入函数。 无论我如何改变它,当我尝试加载函数时,它都会导致一个NameError 模块代码结构为: def myfunc(params): return sum(params) # this is just a simple example for demonstration class Pipeline: def loadfunc(self,filename): path, modul = arc_filename.rsplit('
def myfunc(params):
return sum(params) # this is just a simple example for demonstration
class Pipeline:
def loadfunc(self,filename):
path, modul = arc_filename.rsplit('\\', 1)
modul = modul[:-3] # removing the .py ending
sys.path.insert(1, path)
exec('from ' + modul + ' import *')
### debug prints: ####
if ('myfunc' in dir(modul) and modul.isfunction(modul.myfunc)):
print('myfunc is defined as function in modul ', modul)
if modul in sys.modules:
print(modul, 'was imported successfully')
else:
print(modul, 'was not imported')
try:
myfunc
except NameError:
print("myfunc not in scope!")
else:
print("myfunc in scope!")
类别代码结构为:
def myfunc(params):
return sum(params) # this is just a simple example for demonstration
class Pipeline:
def loadfunc(self,filename):
path, modul = arc_filename.rsplit('\\', 1)
modul = modul[:-3] # removing the .py ending
sys.path.insert(1, path)
exec('from ' + modul + ' import *')
### debug prints: ####
if ('myfunc' in dir(modul) and modul.isfunction(modul.myfunc)):
print('myfunc is defined as function in modul ', modul)
if modul in sys.modules:
print(modul, 'was imported successfully')
else:
print(modul, 'was not imported')
try:
myfunc
except NameError:
print("myfunc not in scope!")
else:
print("myfunc in scope!")
我还尝试以不同的方式在类方法中进行导入:
class Pipeline:
def loadfunc(self,filename):
path, modul = arc_filename.rsplit('\\', 1)
modul = modul[:-3] # removing the .py ending
os.chdir(path)
exec('from ' + modul + ' import *')
### debug prints: ####
if ('myfunc' in dir(modul) and modul.isfunction(modul.myfunc)):
print('myfunc is defined as function in modul ', modul)
if modul in sys.modules:
print(modul, 'was imported successfully')
else:
print(modul, 'was not imported')
try:
myfunc
except NameError:
print("myfunc not in scope!")
else:
print("myfunc in scope!")
进口方法的不同并不重要。如果我只是尝试运行
myfunc
,代码将始终打印“myfunc不在范围内”或产生NameError。我必须将它放在全局范围内,并将函数itseld导入类方法
这不是我一直在寻找的优雅的解决方案,但似乎是唯一可行的方法。我过去曾尝试过一种优雅的解决方案,但我发现它并未遭到反对。你有没有见过我以前用过@bluetooth?我读过一些关于importlib解决方案的文章,我觉得有点过头了,但最后我可能会试试。@bluetooth谢谢!