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

标签 python import namespaces

我遇到以下代码的问题:

在.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/

相关文章:

python - sumproduct 2 具有 nan 值的数据帧

Python导入错误: No module named pybluez

javascript - 语法错误 : Unexpected token import - Node. js

c# - namespace 和表共享相同的名称(哎呀!)

c++ - 如何声明在不同命名空间中定义的结构?

python - Django 1.6 : How to access static files in view

python - 在 Raspberry Pi 3 上使用 cron 打开和关闭 USB 端口

namespaces - 禁用删除命名空间 - Kubernetes

c++ - 如何打包python模块依赖的共享对象?

Java导入包(打包到当前工作目录之上)