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
fushall
V2EX  ›  Python

python3.6 如何在不改变模块的函数 A(A 调用了另一个模块的函数 B)的情况下,把 B 函数换成自己的?

  •  
  •   fushall · 2018-04-13 09:04:54 +08:00 · 2756 次点击
    这是一个创建于 2197 天前的主题,其中的信息可能已经有所发展或是发生改变。
    是这样的,我有三个模块,分别为 api, print_something, main

    # api.py 如下:
    def myprint(s):
    print(s)

    # print_something.py 如下:
    from api import myprint

    def print_helloworld():
    myprint('helloworld')

    # main.py 如下:

    from print_something import print_helloword

    if __name__ == '__main__':
    print_helloword()

    那么问题来了:
    1. 可否在 main.py 文件中,在不改 api.py 模块的情况下,把 myprint()函数换成其他函数,比如 printttttt()
    2. 我该怎么做?

    请求大家帮助,提前谢谢啦
    6 条回复    2018-04-13 09:20:48 +08:00
    goodryb
        1
    goodryb  
       2018-04-13 09:07:06 +08:00
    我觉得楼主的想法很先进,楼下应该知道怎么做
    wwqgtxx
        2
    wwqgtxx  
       2018-04-13 09:09:58 +08:00   ❤️ 1
    你需要在 import print_something 之前先 import api,然后执行 api.myprint = XXXXXXXXX,之后再 import print_something
    hourann
        3
    hourann  
       2018-04-13 09:15:31 +08:00 via iPhone
    # print_something.py
    def print_helloworld(func=myprint):
    func(‘ hello world ’)
    # main.py
    print_helloworld(printtttt)

    是不是你想要的
    Cooky
        4
    Cooky  
       2018-04-13 09:16:03 +08:00 via Android   ❤️ 1
    import print_something
    print_something.myprint = xxxxx
    crb912
        5
    crb912  
       2018-04-13 09:16:52 +08:00 via Android   ❤️ 1
    楼上正解,import 不一定要放在源码的头部,你可以在快要使用的时候函数前,才进行 import。
    fushall
        6
    fushall  
    OP
       2018-04-13 09:20:48 +08:00
    @wwqgtxx 谢谢你,果然可以
    附上代码:

    # main.py 代码如下:
    import api
    def printttttt(s):
    print('666666')

    api.myprint = printttttt

    from print_something import print_helloworld


    if __name__ == '__main__':
    print_helloword()

    >>> 666666
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3070 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:33 · PVG 22:33 · LAX 07:33 · JFK 10:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.