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

【Python】decoratorとmetaclassでclass変数をいじる方法

Posted at

デコレーターを用いてハンドリング処理などを簡潔に書きたい時に、metaclassを使うけれど、やりかたをいつも忘れるのでメモ

from types import MethodType, FunctionType, LambdaType

class MetaClass(type):
    def __new__(cls, name, bases, attr):
        def is_excutable(v):
            return isinstance(v, (MethodType, FunctionType, LambdaType))

        target = attr['target']

        for k, v in attr.items():
            if is_excutable(v) and getattr(v, '__flag', False):
                target.append((getattr(v, '__command'), v))

        klass = type.__new__(cls, name, bases, attr)
        klass.target = target
        return klass


def decorator(command=''):
    def decorate(func):
        setattr(func, '__flag', True)
        setattr(func, '__command', command)
        return func
    return decorate

class Klass(metaclass=MetaClass):
    target = []

    @decorator('command_name')
    def test_method(self):
        pass

print('Klass.target:', Klass.target)
2
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
2
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?