相关疑难解决方法(0)

如何在不为每种方法反复输入的情况下装饰类的所有函数?

让我说我的类有很多方法,我想在每一个方法上应用我的装饰,后来当我添加新方法时,我想要应用相同的装饰器,但我不想在方法声明之上写@mydecorator所有时间?

如果我调查的__call__是正确的方法吗?

重要提示:以下示例似乎解决了与原始问题不同的问题.

编辑:我想以这种方式展示,这是我的问题的类似解决方案,对于任何人后来发现这个问题,使用评论中提到的mixin.

class WrapinMixin(object):
    def __call__(self, hey, you, *args):
        print 'entering', hey, you, repr(args)
        try:
            ret = getattr(self, hey)(you, *args)
            return ret
        except:
            ret = str(e)
            raise
        finally:
            print 'leaving', hey, repr(ret)
Run Code Online (Sandbox Code Playgroud)

然后你可以在另一个

class Wrapmymethodsaround(WrapinMixin): 
    def __call__:
         return super(Wrapmymethodsaround, self).__call__(hey, you, *args)
Run Code Online (Sandbox Code Playgroud)

python decorator wrapper

52
推荐指数
5
解决办法
3万
查看次数

如何使用`functools.lru_cache`正确装饰`classmethod`?

我试图 classmethodfunctools.lru_cache. 我的尝试失败了:

import functools
class K:
    @functools.lru_cache(maxsize=32)
    @classmethod
    def mthd(i, stryng: str): \
        return stryng

obj = K()
Run Code Online (Sandbox Code Playgroud)

错误消息来自functools.lru_cache

TypeError: the first argument must be callable
Run Code Online (Sandbox Code Playgroud)

python static-methods decorator python-3.x python-decorators

7
推荐指数
2
解决办法
2055
查看次数