加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python导入的模块是None

发布时间:2020-12-16 21:59:04 所属栏目:Python 来源:网络整理
导读:我有一个导入正常的模块(我将它打印在使用它的模块的顶部) from authorize import cimprint cim 哪个产生: 但是后来在方法调用中,它神秘地转向了None class MyClass(object): def download(self): print cim 运行时显示cim为None.在此模块中,模块不会直接分

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

from authorize import cim
print cim

哪个产生:

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

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

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

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

最佳答案
当你自己评论时 – 很可能有些代码将None归因于模块本身的“cim”名称 – 检查这个的方法是你的大模块是否只为其他模块“只读” – 我认为Python允许这个 –

(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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读