推荐学习书目
› 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 · Apr 13, 2018 · 3772 views
    This topic created in 3132 days ago, the information mentioned may be changed or developed.
    是这样的,我有三个模块,分别为 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 replies  •  2018-04-13 09:20:48 +08:00
    goodryb
    goodryb
    Apr 13, 2018
    1
    我觉得楼主的想法很先进,楼下应该知道怎么做
    wwqgtxx
    wwqgtxx
    Apr 13, 2018❤️1
    2
    你需要在 import print_something 之前先 import api,然后执行 api.myprint = XXXXXXXXX,之后再 import print_something
    hourann
    hourann
    Apr 13, 2018 via iPhone
    3
    # print_something.py
    def print_helloworld(func=myprint):
    func(‘ hello world ’)
    # main.py
    print_helloworld(printtttt)

    是不是你想要的
    Cooky
    Cooky
    Apr 13, 2018 via Android❤️1
    4
    import print_something
    print_something.myprint = xxxxx
    crb912
    crb912
    Apr 13, 2018 via Android❤️1
    5
    楼上正解,import 不一定要放在源码的头部,你可以在快要使用的时候函数前,才进行 import。
    fushall
    fushall
    OP
    Apr 13, 2018
    6
    @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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4532 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 08:19 · PVG 16:19 · LAX 00:19 · JFK 03:19
    ♥ Do have faith in what you're doing.