python - 这是 Python 中某种类型的装饰器吗?

标签 python decorator

我一直在阅读一些代码,并在下面发现了这一点。

我不明白@SdServer.appId(APP_ID)是否是装饰器。它具有来自装饰器的 @,但类方法 appId 看起来不像我习惯的装饰器语法。我不明白这是在做什么。

我在 SdApp 类中查找 appID 最后包含的打印语句返回以下内容:

SdApp class instance ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'request'] 

SdApp instance request ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] 

method list ['request']

代码

APP_ID = 'oA'

class SdServer(object):
    APP_ID_HANDLERS = {}

    def __init__(self, originator):
        self.originator = originator

    @classmethod
    def appId(cls, appId):
        def _handler(f):
            cls.APP_ID_HANDLERS[appId] = f
            return f

        return _handler


@SdServer.appId(APP_ID)
class SdApp(object):
    @classmethod
    def request(cls, originator, body=None):
        try:
            print(cls)
        except OException as e:
            log.error('Cannot process request: %s', e)

# me trying to figure out what it is doing below

first = SdApp()

print('SdApp class instance', dir(first), '\n')
print('SdApp instance request', dir(first.request), '\n')

method_list = [func for func in dir(SdApp) if callable(getattr(SdApp, func)) and not func.startswith("__")]

print('method list', method_list)

最佳答案

类方法本身不是装饰器,而是它的返回值。在您的示例中,@SdServer.appId(APP_ID) 将调用类方法并将结果用作装饰器。进一步按照您的示例,这将是 _handler 函数,它似乎使用 SdServer 类注册装饰类。返回的装饰器包含对 cls 和 appId 变量的闭包,因此实现有些复杂。

关于python - 这是 Python 中某种类型的装饰器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52447095/

相关文章:

python - 使用 nopython 模式在 numba 装饰器@njit 中为字符串的 ndarray 签名

python - zsh:未找到匹配项:请求 [安全]

python - 当尺寸为 63 和 27 时,填充不起作用

python - 使用广泛重用的装饰器分析系统

javascript - 创建 jquery 对话框 RactiveJS 装饰器

python - 描述符 'getter' 需要一个 'property' 对象,但收到一个 'function'

python - 使用链接的 "join"连接多个数据帧(而不是合并或连接)是否有效?

python - 需要使用 beautifulsoup 提取所有字体大小和文本

python - Keras MSE 定义

使用 Django 的 Ajax View