我想要创建一个python装饰器,它将某个函数添加到该类的函数列表中,这些函数有时会被处理。示例代码:
class A:
# every subclass should define _list
@classmethod
def decorator(cls, f):
# cls = B
cls._flist.append(f)
return f
@classmethod
def processFunctions(cls):
for f in cls._flist:
...
class B(A):
_flist = []
@B.decorator # Obviously not possible because cls is not defined (yet)
def foo(self):
print("Inside foo")有可能复制这种行为吗?类( cls )应该在修饰函数时传递,因此我不能使用通常的方法来创建包装器函数“解包”cls和其他参数。
发布于 2022-08-12 21:01:46
好吧,我想我已经解决了一些问题。
您需要A的一个实例,但是作为B中的类变量。
然后,每个方法都需要一个实例:
class A:
def __init__(self):
self._flist = []
def decorator(self, f):
self._flist.append(f)
return f
def processFunctions(self, other):
for f in self._flist:
f(other)
class B:
a=A()
@a.decorator
def foo(self):
print("Inside foo")
def processFunctions(self):
B.a.processFunctions(self)
b = B()
b.processFunctions()输出
Inside foo发布于 2022-08-12 21:15:34
下面的方法是基于locals()在CPython中的实现行为,但是有PEP 558使其成为文档化的标准行为:
class A:
# every subclass should define _list
@staticmethod
def decorator(loc):
def registrator(f):
loc['_flist'].append(f)
return f
return registrator
@classmethod
def processFunctions(cls):
for f in cls._flist:
...
class B(A):
_flist = []
@decorator(locals())
def foo(self):
print("Inside foo")发布于 2022-08-15 08:06:46
另一种方法,如包ABC使用的方法,是让装饰器向函数添加一个标志,然后遍历这个类的函数,这些函数激活了该标志。
class A:
@staticmethod
def decorator(f):
def wraps(f)
f.__processable__ = True
return f
return wraps
def processFunctions(self):
for d in dir(self):
try:
f = getattr(self, d).__func__
if f.__processable__:
f() # Or whatever we want to do with the function
# Instead of try/except we could use a bunch of nested ifs
except AttributeError:
passhttps://stackoverflow.com/questions/73339488
复制相似问题