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

Python 实现类里的装饰器问题

  •  
  •   yellowmarlboro · 2020-12-11 17:33:25 +08:00 · 1234 次点击
    这是一个创建于 1254 天前的主题,其中的信息可能已经有所发展或是发生改变。

    code

    class A:
        key: str = None
        sleep_seconds: int = 10
    
        def run_forever(func):
    
            @wraps(func)
            def wrapped(self, *args, **kwargs):
                while True:
                    func(self, *args, **kwargs)
                    time.sleep(self.sleep_seconds)
    
            return wrapped
    
    
        @run_forever
        def test(self):
            print(123)
    
    A().test()
    
    

    这样虽然可以,但是 pycharm 标黄,而且觉得写的不对。另装饰器用到了类的参数。 有没有更好 /正确的写法? 虽然这样没问题,但是

    1 条回复    2020-12-11 17:37:12 +08:00
    frostming
        1
    frostming  
       2020-12-11 17:37:12 +08:00
    当然是用 descriptor,把 func 包一层

    def __get__(self, ins, kls)

    里面就能拿到类的参数,然后返回一个更新了的自己
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2228 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 89ms · UTC 06:31 · PVG 14:31 · LAX 23:31 · JFK 02:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.