推荐学习书目
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
chu1337
V2EX  ›  Python

Python 引用 调用上级函数

  •  
  •   chu1337 ·
    Q2h1Cg · Oct 8, 2014 · 5064 views
    This topic created in 4262 days ago, the information mentioned may be changed or developed.

    a.py

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

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

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

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

    var = 'var in a'

    这样?不从顶层 import b,在需要用到的函数里面 import b?
    royzhanggy
        11
    royzhanggy  
       Oct 8, 2014
    @billlee 有个问题不怎么明白,刚才试了下交叉引用模块,结果直接python b.py执行是错误的,显示AttributeError,可是在交互系统里直接import b的时候却没出错....python的import机制真是让人摸不着头脑
    WKPlus
        12
    WKPlus  
       Oct 9, 2014   ❤️ 1
    python不会重复import同一个module,两个module可以循环引用,但使用不当还是会有问题,比如这里http://blog.jobbole.com/68256/的常见错误7,其实主要是要搞清楚代码执行的顺序。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5941 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 58ms · UTC 02:52 · PVG 10:52 · LAX 19:52 · JFK 22:52
    ♥ Do have faith in what you're doing.