LoginSignup
4
5

More than 5 years have passed since last update.

class のなかに decorator を書く

Last updated at Posted at 2015-05-26


理解したら簡単だけどなにかとむずかしいデコレーター
もうバッチリだぜとおもってクラス内に記述したらちょっと泣いた
*args うけとって args[0] を渡すといいっぽいです

yo.py

import functools
import random

class Prot:
    def __init__(self):
        self.yo = ['yo'*i for i in range(10)] 

    def yoyo(f):
        functools.wraps(f)
        def wraps(*args):
            print('yo gacha.')
            result = f(args[0]) #  args[0] = self, result = return value
            print('')
            return result
        return wraps

    @yoyo
    def yo_gacha(self):
        print(self.yo[random.randint(0, 9)])    

if __name__ == '__main__':
    p = Prot()
    for _ in range(2): p.yo_gacha()    
~ %python -m yo
yo gacha.
yoyoyoyo

yo gacha.
yoyoyoyoyoyoyoyoyo

~ %

つづく

=> to be continued...

4
5
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
4
5