3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】使い道があるようでなさそうなデコレータつくった。

3
Last updated at Posted at 2020-03-12

はじめに

皆さんデコレータ作ってますか? 恥ずかしながら、私は今日詳細を知りました。存在には気づいていても今日までは無視してきましたが、勉強しましたので何かアウトプットしようと思って書いています。

つくったもの

早速ですがこんなものをつくてみました。

deco_test.py
def decof(Func,*_args,**_kwargs):
    def _deco(func):
        def wrapper(*args,**kwargs):
            return Func(func(*args,**kwargs),*_args,**_kwargs)
        return wrapper
    return _deco

def decob(Func,*_args,**_kwargs):
    def _deco(func):
        def wrapper(*args,**kwargs):
            return Func(*_args,func(*args,**kwargs),**_kwargs)
        return wrapper
    return _deco

ざっくり説明すると、どちらもラップされる関数の戻り値を指定した関数に受け取らせる関数が作れます。
2つあるのは戻り値を第一引数として受け取るか(decof())一番うしろの引数に受け取るか(decob())で使い分けるためです。
言葉だとわかりにくいので実演すると、

deco_test.py
import numpy as np
from functools import reduce
from operator import sub

@decob(reduce,sub)
@decof(np.array,dtype=int)
@decof(list)
@decof(str)
@decob(pow,2)
@decof(pow,2)
def add(a,b):return a+b

print(add(3,4))
出力
-55
# 3+4 -> 7**2 -> 2**49 -> '562949953421312' -> ['5', '6', '2', '9', '4', '9', '9', '5', '3', '4', '2', '1', '3', '1', '2']
# -> array([5, 6, 2, 9, 4, 9, 9, 5, 3, 4, 2, 1, 3, 1, 2]) -> 5-6-2-9-4-9-9-5-3-4-2-1-3-1-2 -> -55

こんな感じの関数リレーをスッキリ(?)表現できます。
以上です。

まとめ

今まで避けてきましたが使い方次第ではかなり便利そうなので、また何か思いついたらここで紹介できたらと思います。最後まで読んでくださりありがとうございました。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?