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

学习装饰器过程遇到一个困扰,请指教

  •  
  •   huangmiao233 · Oct 27, 2018 · 2955 views
    This topic created in 2938 days ago, the information mentioned may be changed or developed.
    def outer(some_func):
         def inner():
             print ("before some_func")
             ret = some_func()
             return ret
         return inner
    
    def foo():
         return 3
    
    outer(foo)()
    

    执行的结果是 before some_func

    环境是 python3.6,按思路来说 ret 也应当被打印出来吧?我尝试改成 return print(ret)才能把 3 打印出来。但是不能理解。请各路大佬指点下,谢谢!

    7 replies  •  2018-10-31 05:11:29 +08:00
    huangmiao233
    huangmiao233
    OP
    Oct 27, 2018
    1
    好糟糕的编辑。。
    so1n
    so1n
    Oct 27, 2018 via Android
    2
    没 print 怎么打印输出……
    zhzer
    zhzer
    Oct 27, 2018 via Android
    3
    是 ide 没自动 echo 吧,你没打印它肯定不出来啊
    newtype0092
    newtype0092
    Oct 27, 2018
    4
    你按什么思路觉得 ret 应当被打印出来?我不太懂 python,但整个代码只有一句 print ("before some_func"),打印出其他东西才不正常吧?
    ifhwhlwpto
    ifhwhlwpto
    Oct 27, 2018
    5
    如果你用 IDLE 的话能看到 3
    ```
    >>> outer(foo)()
    before some_func
    3
    ```
    huangmiao233
    huangmiao233
    OP
    Oct 27, 2018
    6
    @ifhwhlwpto
    @newtype0092
    @so1n
    @zhzer
    @newtype0092 多谢各位确实是我理解有问题。用 IDLE 是 OK 的,我傻了 在 pycharm 运行是不打印的。
    tz1006
    tz1006
    Oct 31, 2018
    7
    ret 是被 return 的而不是 print,实际运行中你不会看到 return 但是你手动执行后 return 会显示出来,但实际上并不是 print。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2045 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 15:18 · PVG 23:18 · LAX 07:18 · JFK 10:18
    ♥ Do have faith in what you're doing.