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

装饰器问题

  •  
  •   sasic · 2019-03-21 23:43:11 +08:00 via iPhone · 1438 次点击
    这是一个创建于 1854 天前的主题,其中的信息可能已经有所发展或是发生改变。
    关于 Python 装饰器问题
    想在同一 class 下,用方法 A 装饰方法 B,功能比如说:在 B 执行完,print 属性 C 可行吗?
    4 条回复    2019-03-26 18:14:55 +08:00
    sasic
        1
    sasic  
    OP
       2019-03-21 23:46:28 +08:00 via iPhone
    class school():
    def __init__(self, c):
    self.c=c
    def A
    def B
    aijam
        2
    aijam  
       2019-03-22 00:24:20 +08:00
    yes and no。这只是一个 anti-pattern workaround,注意这里的 decorator 不是 method。虽然也可以定义成 method,但是需要更多的 hack。
    https://gist.github.com/czheo/a976c92f60c6757f6e9dd316174eea6f
    sasic
        3
    sasic  
    OP
       2019-03-22 09:02:27 +08:00
    @aijam 非常感谢,可以举个例吗?网址好像打不开
    shyrock
        4
    shyrock  
       2019-03-26 18:14:55 +08:00
    是不是这样?
    class school():
    def __init__(self,c):
    self.c = c
    def A(func):
    def dec(self):
    result = func(self)
    print(self.c)
    return result
    return dec
    @A
    def B(self):
    print('exec B()')
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3250 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:52 · PVG 20:52 · LAX 05:52 · JFK 08:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.