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

请问这个理解对不对

  •  
  •   saximi · Jul 6, 2017 · 1766 views
    This topic created in 3232 days ago, the information mentioned may be changed or developed.
    装饰器是在导入模块时立即执行的,所以装饰函数中的代码在导入模块时会被执行,
    但是装饰函数中如果有__init__或__call__模块,这些模块中的代码在导入时是不会被执行的。
    3 replies    2017-07-07 20:56:13 +08:00
    sagaxu
        1
    sagaxu  
       Jul 7, 2017 via Android
    不对
    saximi
        2
    saximi  
    OP
       Jul 7, 2017
    那么正确的说法应该是什么呢?我是自己测试了一下,发现__init__和__call_中的代码在导入模块时没有执行才有此疑问的,恳请指点!
    saximi
        3
    saximi  
    OP
       Jul 7, 2017
    补充举例如下,例如对于以下的代码,如果只是导入模块,那么不会有输出,但是语句 1 实例化后才会执行__init__,而语句 2 才会执行__call__。

    class Deco:
    def __init__(self,func):
    self.func=func
    print("__init__执行完毕。func=",self.func)
    def __call__(self,*arg,**arg2):
    print("开始执行__call__。")
    self.func('abc')
    print(self,arg,arg2)

    class MyCls():
    @Deco
    def myFunc(self):
    print('this is my work arg is %s'%self)

    deco=Deco(mycls.myFunc) #语句 1
    deco(sendarg='abcdefg') #语句 2
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1540 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 16:47 · PVG 00:47 · LAX 09:47 · JFK 12:47
    ♥ Do have faith in what you're doing.