如何通过decorator打印函数中活动变量的名称Python 3
因此,我有以下代码:如何通过decorator打印函数中活动变量的名称Python 3,python,python-3.x,python-decorators,Python,Python 3.x,Python Decorators,因此,我有以下代码: def checkScope(f): def inner(*args): res=f(*args) // I WANNA PRINT HERE BIM BUM AND BAM return res return inner class A(): @checkScope def first(self): bim = 5 return self.second(bim
def checkScope(f):
def inner(*args):
res=f(*args)
// I WANNA PRINT HERE BIM BUM AND BAM
return res
return inner
class A():
@checkScope
def first(self):
bim = 5
return self.second(bim)
def second(self,m):
if m < 8:
bum = 6
return self.third()
def third(self):
bam=2
return bam
test=A()
test.first()
def检查范围(f):
def内部(*args):
res=f(*args)
//我想在这里打印BIM BUM和BAM
返回res
返回内部
类别A():
@检查镜
def优先(自我):
bim=5
返回自我秒(bim)
def秒(自我,m):
如果m<8:
bum=6
返回self.third()
第三名(自我):
bam=2
返回bam
test=A()
test.first()
如何使用Inspect在函数checkScope中打印变量bim bum和bam?装饰程序无法在行之间放置命令。您的变量只存在于函数的运行时,因此它们不能在其他任何地方读取。您必须将它们定义为类变量或变量
你可以做的一件事是将它们作为参数传递并读取它们。当你说“我想在这里打印BIM BUM和BAM”时,这些变量实际上都不存在——作为局部变量,它们在包含函数的末尾消失了。正如@jasonharper提到的,您不能这样做,因为此时变量不再存在。您可以编写一个decorator,如果在
第三个
函数中使用它,则可以使用inspect.currentframe
和inspect.outerframes
的组合来检查所有外部作用域的局部变量,但我相当确信,没有办法创建一个装饰器,它可以为您提供使用它的函数的局部变量。您必须在函数调用本身中确定这一点。