Automatically decorating every instance method in a class

前端 未结 2 568
耶瑟儿~
耶瑟儿~ 2021-02-05 22:40

I want to apply the same decorator to every method in a given class, other than those that start and end with __.

It seems to me it should be doable using

2条回答
  •  北海茫月
    2021-02-05 23:37

    You could do this (not sure if this is the most elegant way though):

    def get_all_instance_methods(x):
        return filter(callable, map(lambda d: getattr(x, d), dir(x)))
    

    As for the cls.method_name, you will have to use getattr(cls, method_name).

提交回复
热议问题