另一个文件的python加载类名总是失败

时间:2013-12-09 06:54:10

标签: python import namespaces

我遇到以下代码问题:

在a.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!

我知道在a.py文件中,F类对象不能知道'CB'类,但我该如何解决这个问题呢?我需要遵循这种格式,但我尝试编辑globals(),没有运气。

1 个答案:

答案 0 :(得分:1)

因为在a.py中,它不知道CB,全局变量不会有CB。但是f在a.py中,所以你必须告诉他,就像这样:

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在globals中调用