V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Dec 11, 2020 · 1648 views
    This topic created in 1964 days ago, the information mentioned may be changed or developed.

    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 replies    2020-12-11 17:37:12 +08:00
    frostming
        1
    frostming  
       Dec 11, 2020
    当然是用 descriptor,把 func 包一层

    def __get__(self, ins, kls)

    里面就能拿到类的参数,然后返回一个更新了的自己
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3538 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 11:57 · PVG 19:57 · LAX 04:57 · JFK 07:57
    ♥ Do have faith in what you're doing.