0
0

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 3 years have passed since last update.

【Python】進化する関数

Last updated at Posted at 2021-07-25

What's this?

あと付けで機能を足せる関数です。使い道は思いつきません。
何か思いついたらコメントで教えていただけると嬉しいです。

def evolvableFunc(*keys):
    for name, f in evolvableFunc.__dict__.items():
        if callable(f):
            evolvableFunc.__dict__[name] = f(**f.__dict__)
    return tuple([evolvableFunc.__dict__[key] for key in keys])

evolvableFunc.関数名 = 関数で持たせた関数を順に実行します。
関数に渡す引数はevolvableFunc.関数名.引数名 = 引数で定義します。
実行結果は関数名のローカル変数に保存されます。
evolvableFunc呼び出し時に引数として文字列で関数名を渡せば、タプルで実行結果を受け取れます。

Python3.6から辞書の順番は保持されるらしいので、恐らく定義順で実行されるはず。

例1

evolvableFunc.f1 = lambda a: a*a
evolvableFunc.f1.a = 6
evolvableFunc.f2 = lambda: evolvableFunc.f1+5
print(evolvableFunc('f2'))  # -> (41,)

例2

evolvableFunc.f3 = lambda : not any([evolvableFunc.f2%i==0 for i in range(2, int(evolvableFunc.f1**.5)+1)])
evolvableFunc('f1', 'f2', 'f3')  # -> (36, 41, True)

例3

def f4(x):
    for i in range(x):
        print(i)
    return i>5
evolvableFunc.f4 = f4
evolvableFunc.f4.x = 6
evolvableFunc('f4')  # -> (False,)
'''stdout
0
1
2
3
4
5
'''
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?