我一直在阅读一些代码,并在下面发现了这一点。
我不明白@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/