您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python导入的模块是None

5b51 2022/1/14 8:20:52 python 字数 3506 阅读 472 来源 www.jb51.cc/python

我有一个导入正常的模块(我将它打印在使用它的模块的顶部)from authorize import cim print cim 哪个产生:<module 'authorize.cim' from '.../dist-packages/authorize/cim.pyc'> 但是后来在方法调用中,它神秘地转向了Noneclass MyClass(o

概述

我有一个导入正常的模块(我将它打印在使用它的模块的顶部)

from authorize import cim
print cim

哪个产生:


  

但是后来在方法调用中,它神秘地转向了None

class MyClass(object):
    def download(self):
        print cim

运行时显示cim为None.在此模块中,模块不会直接分配给None.

任何想法如何发生这种情况?

(20分钟黑客攻击) –

这里 – 只需将此代码段放在“protect_module.py”文件中,导入并调用即可
名称“cim”消失的模块末尾的“ProtectdedModule()” –
它应该给你罪魁祸首:

"""
Protects a Module against naive monkey patching  -
may be usefull for debugging large projects where global
variables change without notice.

Just call the "ProtectedModule"  class,with no parameters from the end of 
the module deFinition you want to protect,and subsequent assignments to it
should fail.

"""

from types import ModuleType
from inspect import currentframe,getmodule
import sys

class ProtectedModule(ModuleType):
    def __init__(self,module=None):
        if module is None:
            module = getmodule(currentframe(1))
        ModuleType.__init__(self,module.__name__,module.__doc__)
        self.__dict__.update(module.__dict__)
        sys.modules[self.__name__] = self

    def __setattr__(self,attr,value):
        frame = currentframe(1)
        raise ValueError("Attempt to monkey patch module %s from %s,line %d" % 
            (self.__name__,frame.f_code.co_filename,frame.f_lineno))        

if __name__ == "__main__":
    from xml.etree import ElementTree as ET
    ET = ProtectedModule(ET)
    print dir(ET)
    ET.bla = 10
    print ET.bla

总结

以上是编程之家为你收集整理的Python导入的模块是None全部内容,希望文章能够帮你解决Python导入的模块是None所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶