我有问题,解决这个问题,我有下面的类:工作和getattr的
class test:
@auth
def method1(self, x):
return x
@auth
def method2(self, x, y):
return x+y
def method3(self, z):
return z
我申请的装饰在这两种方法,如下:
class auth:
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
self.f(*args, **kwargs)
到目前为止没有问题,不过,我需要(需要)使用下面的代码:
def run():
klass = globals()["test"]()
method1 = getattr(klass, "method1")
print(method1.__code__.co_varnames)
# should print (self, x)
method2 = getattr(klass, "method2")
print(method2.__code__.co_varnames)
# should print (self, x, y)
method3 = getattr(klass, "method3")
print(method3.__code__.co_varnames)
# i get (self, z) < without decorator
但我现在得到:
AttributeError: 'auth' object has no attribute '__code__'
如果我们认为方法“method1和method2”的签名现在是“auth”,那么有意义。
那么,如何获得有或没有装饰器的参数。 我开始阅读有关“检查”的内容,但有很多关于缓慢的报道。
你可以使用像'method1.f .__ code __。co_varnames'这样的东西。但是通常你需要使用的代码需要知道/与装饰器代码协作(即它需要知道在哪里寻找函数参数)。 – BrenBarn