我一直在阅读一些代码,并在下面遇到了这个问题。
我不知道@ 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)
答案 0 :(得分:2)
类方法本身不是装饰器,而是其返回值。在您的示例中,@SdServer.appId(APP_ID)
将调用类方法并将结果用作修饰符。在您的示例之后,这将是_handler
函数,该函数似乎向SdServer
类注册了修饰的类。返回的装饰器包含cls
和appId
变量的闭包,因此实现起来有些复杂。