V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
chuhades
V2EX  ›  Python

Python 引用 调用上级函数

  •  
  •   chuhades ·
    Q2h1Cg · 2014-10-08 20:26:59 +08:00 · 4245 次点击
    这是一个创建于 3458 天前的主题,其中的信息可能已经有所发展或是发生改变。

    a.py

    import b
    
    def fun():
            print "fun in a.py"
    
    var = "var in a"
    

    然后如何在 b.py 中调用 fun 函数和读写 var 变量?
    求大牛教育

    12 条回复    2014-10-09 13:13:27 +08:00
    billlee
        1
    billlee  
       2014-10-08 20:37:45 +08:00
    这个设计很不合理,还是先说说你为什么要这样做吧
    chuhades
        2
    chuhades  
    OP
       2014-10-08 20:47:25 +08:00
    @billlee 写了一个框架,通过调用插件进行扩展。然后有一个插件的功能是实现自动化测试,需要通过框架中的函数调用其他插件并进行一些参数设置。
    billlee
        3
    billlee  
       2014-10-08 21:11:18 +08:00   ❤️ 1
    @chuhades 这样的话,这就是个插件系统的设计问题了。我把问题复述一遍。
    现在有框架 framework, 和插件 plugin-testing. 框架肯定是通过 API 调用插件的,但是这个插件 plugin-testing 比较特殊,还需要访问由 framework 提供的服务。
    那么,要完成这个任务,最直观的方法,是在插件初始化的时候,把相关的引用传递给它。
    应该还有更好的方法吧,但楼主想要引用 importer,应该是没法实现的.
    chuhades
        4
    chuhades  
    OP
       2014-10-08 21:21:30 +08:00
    @billlee 感谢,有了一些思路,虽然达不到我的要求..
    tempdban
        5
    tempdban  
       2014-10-08 21:27:39 +08:00 via Android
    赤裸裸的回调啊
    chuhades
        6
    chuhades  
    OP
       2014-10-08 21:30:14 +08:00
    @tempdban 求详细
    bcxx
        7
    bcxx  
       2014-10-08 21:33:00 +08:00
    用 inspect (不过真的不建议这么写啊- -明显是设计的问题了 你应该反转一下来让那个测试插件来配置全局的
    chuhades
        8
    chuhades  
    OP
       2014-10-08 21:46:57 +08:00
    @bcxx 现在就是纠结于如何通过测试插件来配置全局..
    zlandjj
        9
    zlandjj  
       2014-10-08 22:35:46 +08:00
    用 exec 还有 eval , 理论上你只要能拼出来代码都能调用。
    messense
        10
    messense  
       2014-10-08 22:43:59 +08:00
    解决循环引用的问题?试试:

    def fun():
    ====import b
    ====print 'fun in a.py'

    var = 'var in a'

    这样?不从顶层 import b,在需要用到的函数里面 import b?
    royzhanggy
        11
    royzhanggy  
       2014-10-08 22:49:36 +08:00
    @billlee 有个问题不怎么明白,刚才试了下交叉引用模块,结果直接python b.py执行是错误的,显示AttributeError,可是在交互系统里直接import b的时候却没出错....python的import机制真是让人摸不着头脑
    WKPlus
        12
    WKPlus  
       2014-10-09 13:13:27 +08:00   ❤️ 1
    python不会重复import同一个module,两个module可以循环引用,但使用不当还是会有问题,比如这里http://blog.jobbole.com/68256/的常见错误7,其实主要是要搞清楚代码执行的顺序。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3400 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:18 · PVG 19:18 · LAX 04:18 · JFK 07:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.