如何使用给定的装饰器获取python类的所有方法

如何使用给定的装饰器获取python类的所有方法,第1张

如何使用给定的装饰器获取python类的所有方法 方法1:基本注册装饰器

我已经在这里回答了这个问题:在Python中通过数组索引调用函数=)


方法2:源代码解析

如果您无法控制 定义,而 _ _定义 是您想假设的一种解释,则这是 不可能的 (没有代码的读取-
反射),因为装饰器可以是无 *** 作的装饰器(例如在我的链接示例中)仅返回未修改的函数。(但是,如果您允许自己包装/重新定义装饰器,请参阅
方法3:将装饰器转换为“具有自我意识” ,那么您将找到一个优雅的解决方案)

这是一个可怕的骇客,但是您可以使用该

inspect
模块读取源代码本身并进行解析。这在交互式解释器中将不起作用,因为检查模块将拒绝以交互方式提供源代码。但是,以下是概念证明。

#!/usr/bin/python3import inspectdef deco(func):    return funcdef deco2():    def wrapper(func):        pass    return wrapperclass Test(object):    @deco    def method(self):        pass    @deco2()    def method2(self):        passdef methodsWithDecorator(cls, decoratorName):    sourcelines = inspect.getsourcelines(cls)[0]    for i,line in enumerate(sourcelines):        line = line.strip()        if line.split('(')[0].strip() == '@'+decoratorName: # leaving a bit out nextLine = sourcelines[i+1] name = nextLine.split('def')[1].split('(')[0].strip() yield(name)

有用!:

>>> print(list(  methodsWithDecorator(Test, 'deco')  ))['method']

请注意,必须注意解析和python语法,例如

@deco
@deco(...
是有效结果,但
@deco2
如果仅要求则不应返回
'deco'
。我们注意到,根据http://docs.python.org/reference/compound_stmts.html上的官方python语法,装饰器如下:

decorator      ::=  "@" dotted_name ["(" [argument_list [","]] ")"] newline

不必处理诸如此类的案件,我们松了一口气

@(deco)
。但请注意,这仍然没有真正帮助你,如果你真的很复杂的装饰,例如
@getDecorator(...)
,如

def getDecorator():    return deco

因此,这种分析代码的“尽力而为”策略无法检测到这种情况。尽管如果您正在使用此方法,那么您真正想要的是定义中该方法顶部的内容,在本例中为

getDecorator

根据规范,

@foo1.bar2.baz3(...)
作为装饰者也是有效的。您可以扩展此方法以进行处理。您也可以
<function object...>
花费很多精力来扩展此方法以返回a而不是函数的名称。但是,这种方法是骇人听闻的,而且很糟糕。


方法3:将装饰器转换为“自我意识”

_如果您无法控制 装饰器的* 定义_(这是您想要的另一种解释),那么所有这些问题都会消失,因为您可以控制装饰器的应用方式。因此,您可以通过 包装
装饰器来修改装饰器,以创建 自己的 装饰器,并使用
装饰器装饰功能。让我再说一遍:您可以创建一个装饰器来装饰您无法控制的装饰器,“启发”它,在我们的情况下,这使其可以像以前那样做, 还可以

.decorator
元数据属性附加到它返回的可调用对象上,让您跟踪“此功能是否经过装饰?让我们检查function.decorator!”。

*您可以遍历类的方法,然后检查装饰器是否具有适当的
.decorator
属性!=)如此处所示:

def makeRegisteringDecorator(foreignDecorator):    """        Returns a copy of foreignDecorator, which is identical in every        way(*), except also appends a .decorator property to the callable it        spits out.    """    def newDecorator(func):        # Call to newDecorator(method)        # Exactly like old decorator, but output keeps track of what decorated it        R = foreignDecorator(func) # apply foreignDecorator, like call to foreignDecorator(method) would have done        R.decorator = newDecorator # keep track of decorator        #R.original = func         # might as well keep track of everything!        return R    newDecorator.__name__ = foreignDecorator.__name__    newDecorator.__doc__ = foreignDecorator.__doc__    # (*)We can be somewhat "hygienic", but newDecorator still isn't signature-preserving, i.e. you will not be able to get a runtime list of parameters. For that, you need hackish libraries...but in this case, the only argument is func, so it's not a big issue    return newDecorator

示范

@decorator

deco = makeRegisteringDecorator(deco)class Test2(object):    @deco    def method(self):        pass    @deco2()    def method2(self):        passdef methodsWithDecorator(cls, decorator):    """         Returns all methods in CLS with DECORATOR as the        outermost decorator.        DECORATOR must be a "registering decorator"; one        can make any decorator "registering" via the        makeRegisteringDecorator function.    """    for maybeDecorated in cls.__dict__.values():        if hasattr(maybeDecorated, 'decorator'): if maybeDecorated.decorator == decorator:     print(maybeDecorated)     yield maybeDecorated

有用!:

>>> print(list(   methodsWithDecorator(Test2, deco)   ))[<function method at 0x7d62f8>]

但是,“注册装饰器”必须是 最外面的装饰器 ,否则

.decorator
属性注释将丢失。例如在火车上

@decoOutermost@deco@decoInnermostdef func(): ...

您只能看到

decoOutermost
公开的元数据,除非我们保留对“更内部”包装器的引用。

旁注:以上方法还可以构建一个

.decorator
,以跟踪 整个已应用装饰器和输入函数以及装饰器工厂参数的堆栈
。=)例如,如果考虑注释行
R.original =func
,则可以使用这样的方法来跟踪所有包装层。如果我编写装饰器库,这是我个人要做的事情,因为它允许深入的自省。

@foo
和之间也有区别
@bar(...)
。虽然它们都是规范中定义的“装饰器表达”,但请注意,这
foo
是一个装饰器,同时会
bar(...)
返回动态创建的装饰器,然后将其应用。因此,您需要一个单独的函数
makeRegisteringDecoratorFactory
,该函数有点像,
makeRegisteringDecorator
但甚至需要更多信息:

def makeRegisteringDecoratorFactory(foreignDecoratorFactory):    def newDecoratorFactory(*args, **kw):        oldGeneratedDecorator = foreignDecoratorFactory(*args, **kw)        def newGeneratedDecorator(func): modifiedFunc = oldGeneratedDecorator(func) modifiedFunc.decorator = newDecoratorFactory # keep track of decorator return modifiedFunc        return newGeneratedDecorator    newDecoratorFactory.__name__ = foreignDecoratorFactory.__name__    newDecoratorFactory.__doc__ = foreignDecoratorFactory.__doc__    return newDecoratorFactory

示范

@decorator(...)

def deco2():    def simpleDeco(func):        return func    return simpleDecodeco2 = makeRegisteringDecoratorFactory(deco2)print(deco2.__name__)# RESULT: 'deco2'@deco2()def f():    pass

此生成器工厂包装器也可以工作:

>>> print(f.decorator)<function deco2 at 0x6a6408>

奖金 ,让我们甚至尝试方法#3如下:

def getDecorator(): # let's do some dispatching!    return decoclass Test3(object):    @getDecorator()    def method(self):        pass    @deco2()    def method2(self):        pass

结果:

>>> print(list(   methodsWithDecorator(Test3, deco)   ))[<function method at 0x7d62f8>]

如您所见,与method2不同,@
deco可以正确识别,即使它从未在类中明确编写。与method2不同,如果方法是在运行时添加(手动,通过元类等)或继承的,则此方法也将起作用。

请注意,您还可以装饰一个类,因此,如果您“启发”用于装饰方法和类的装饰器,然后 在要分析的类的主体内
编写一个类,

methodsWithDecorator
则将装饰后的类返回为以及装饰方法。可以认为这是一项功能,但是您可以通过检查装饰器的参数来轻松编写逻辑以忽略那些逻辑,即
.original
实现所需的语义。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5644589.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存