我遇到以下代码的问题:
在.py文件中:
class CA():
def __init__(self):
self.name= 'CA'
class F():
def __init__(self):
self.name = 'F'
def calltest(self, obj_name):
print "globals inside F.calltest:",globals()
obj = globals().get(obj_name)
if obj is None:
raise ValueError("OBJ is not there!")
obj.test()
在 b.py 文件中:
from a import *
class CB(CA):
def __init__(self):
self.name = 'CB'
def test(self):
print 'I am class B!'
if __name__ == '__main__':
print "globals() in main:", globals()
f_obj = F()
f_obj.calltest('CB')
我得到了结果:
globals() in main: {'F': <class a.F at 0x023E8880>, '__builtins__': <module '__builtin__' (built-in)>, 'CB': <class __main__.CB at 0x023E8810>, '__file__': 'C:\\Users\\\Downloads\\testcase\\b.py', '__package__': None, '__name__': '__main__', 'CA': <class a.CA at 0x02366AE8>, }
globals inside F.calltest: {'F': <class a.F at 0x023E8880>, '__builtins__': {'bytearray': <type 'bytearray'>, 'IndexError': <type 'exceptions.IndexError'>, 'all': <built-in function all>, 'help': Type help() for interactive help, or help(object) for help about object., 'vars': <built-in function vars>, 'SyntaxError': <type 'exceptions.SyntaxError'>, 'unicode': <type 'unicode'>, 'UnicodeDecodeError': <type 'exceptions.UnicodeDecodeError'>, 'memoryview': <type 'memoryview'>, 'isinstance': <built-in function isinstance>, 'copyright': Copyright (c) 2001-2012 Python Software Foundation.
File "C:\Users\Downloads\testcase\b.py", line 22, in <module>
f_obj.calltest('CB')
File "C:\Users\lDownloads\testcase\a.py", line 21, in calltest
raise ValueError("OBJ is not there!")
ValueError: OBJ is not there!
我知道在 .py 文件中,F 类对象无法识别 'CB' 类,但是我该如何解决这个问题呢?我需要遵循这种格式,但我尝试编辑 globals(),但没有成功。
最佳答案
因为在a.py中,它不知道CB,globals不会有CB。但是a.py中的F,所以你要告诉他,像这样:
class F():
def __init__(self):
self.name = 'F'
def calltest(self, g, obj_name):
obj = g.get(obj_name)
if obj is None:
raise ValueError("OBJ is not there!")
obj.test()
然后在 b.py main 中:
f_obj = F()
f_obj.calltest(globals(), 'CB')
这个全局变量在 b.py 中调用,CB 在全局变量中
关于python从另一个文件加载类名总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20464846/