【发布时间】:2017-06-12 18:55:54
【问题描述】:
我有解决这个问题的问题,我有以下课程:
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 and method2”的签名现在是“auth”,这有什么意义。
那么我如何获得带有或不带有装饰器的参数。 我开始阅读有关“检查”的内容,但有很多关于速度缓慢的报告。
【问题讨论】:
-
你可以使用
method1.f.__code__.co_varnames之类的东西。但总的来说,您“需要”使用的代码需要了解/与装饰器代码合作(即,它需要知道在哪里查找函数参数)。
标签: python python-3.x