LoginSignup
8
8

More than 5 years have passed since last update.

class のなかに decorator なんて書く必要がなかったんだ ありがとう contextmanager

Posted at

前投稿

よつばと! 凄い かっこいい
デコレーターなんてむずかしいことしないで始めから contextmanager をつかっていればよかったんだ……

yo.py
from contextlib import contextmanager
import random

class Prot:
    def __init__(self):
        pass

    @contextmanager
    def yoyo(self, hey):
        print('gacha.') #  __enter__
        yield hey # as
        print('Everything Done Right.') #  __exit__

    def yo_gacha(self, y):
        yo = [y*i for i in range(10)] 
        return yo[random.randint(0, 9)]    

if __name__ == '__main__':
    p = Prot()
    with p.yoyo('hey') as y:
        print(p.yo_gacha(y))

contextlib.contextmanagerwith をイイ感じに適用してくれるデコレーターで yield をはさんで __enter____exit__ にわけてくれます  
インデントがひとつ犠牲になるけど記述も楽だしとてもわかりやすい
yield で渡すと as で受け取れるのも理解しやすいかんじ

いろいろラップしたいときはデコレーターを使ったほうがイイかもですが 勉強になりました

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8