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

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

  •  
  •   helijia21 · 2018-10-27 01:09:18 +08:00 · 1653 次点击
    这是一个创建于 2000 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2018-10-31 05:11:29 +08:00
    helijia21
        1
    helijia21  
    OP
       2018-10-27 01:11:23 +08:00
    好糟糕的编辑。。
    so1n
        2
    so1n  
       2018-10-27 01:19:48 +08:00 via Android
    没 print 怎么打印输出……
    zhzer
        3
    zhzer  
       2018-10-27 01:20:57 +08:00 via Android
    是 ide 没自动 echo 吧,你没打印它肯定不出来啊
    newtype0092
        4
    newtype0092  
       2018-10-27 01:21:13 +08:00
    你按什么思路觉得 ret 应当被打印出来?我不太懂 python,但整个代码只有一句 print ("before some_func"),打印出其他东西才不正常吧?
    ifhwhlwpto
        5
    ifhwhlwpto  
       2018-10-27 01:21:19 +08:00
    如果你用 IDLE 的话能看到 3
    ```
    >>> outer(foo)()
    before some_func
    3
    ```
    helijia21
        6
    helijia21  
    OP
       2018-10-27 02:34:14 +08:00
    @ifhwhlwpto
    @newtype0092
    @so1n
    @zhzer
    @newtype0092 多谢各位确实是我理解有问题。用 IDLE 是 OK 的,我傻了 在 pycharm 运行是不打印的。
    tz1006
        7
    tz1006  
       2018-10-31 05:11:29 +08:00
    ret 是被 return 的而不是 print,实际运行中你不会看到 return 但是你手动执行后 return 会显示出来,但实际上并不是 print。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4443 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 01:03 · PVG 09:03 · LAX 18:03 · JFK 21:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.