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

请问这个理解对不对

  •  
  •   saximi · 2017-07-06 22:24:47 +08:00 · 1339 次点击
    这是一个创建于 2492 天前的主题,其中的信息可能已经有所发展或是发生改变。
    装饰器是在导入模块时立即执行的,所以装饰函数中的代码在导入模块时会被执行,
    但是装饰函数中如果有__init__或__call__模块,这些模块中的代码在导入时是不会被执行的。
    3 条回复    2017-07-07 20:56:13 +08:00
    sagaxu
        1
    sagaxu  
       2017-07-07 09:32:56 +08:00 via Android
    不对
    saximi
        2
    saximi  
    OP
       2017-07-07 20:50:13 +08:00
    那么正确的说法应该是什么呢?我是自己测试了一下,发现__init__和__call_中的代码在导入模块时没有执行才有此疑问的,恳请指点!
    saximi
        3
    saximi  
    OP
       2017-07-07 20:56:13 +08:00
    补充举例如下,例如对于以下的代码,如果只是导入模块,那么不会有输出,但是语句 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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2234 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 344ms · UTC 02:52 · PVG 10:52 · LAX 19:52 · JFK 22:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.