【问题标题】:How can i print the names of variables alive inside a function via decorator? - Python 3如何通过装饰器在函数内打印活动变量的名称? - 蟒蛇 3
【发布时间】:2021-05-12 13:30:49
【问题描述】:

所以,我有这个代码:

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()

如何在函数 checkScope 中使用 Inspect 打印变量 bim bum 和 bam?

【问题讨论】:

  • 当你说“我想在这里打印 BIM BUM AND BAM”时,这些变量实际上都不存在 - 作为局部变量,它们在结束时消失了包含函数。
  • 正如@jasonharper 提到的,您不能这样做,因为此时变量不再存在。你可以写一个装饰器,如果你在third函数上使用它,你可以使用inspect.currentframeinspect.outerframes的组合检查所有外部作用域的局部变量,但我相当有信心没有办法创建一个装饰器,它可以为您提供使用它的函数的局部变量。您必须在函数调用本身中确定这一点。

标签: python python-3.x python-decorators


【解决方案1】:

装饰器不能在你的行之间放置命令。您的变量仅在函数运行时存在,因此无法在其他任何地方读取。您必须将它们定义为类变量或globals

您可以做的一件事是将它们全部作为参数传递并读取它们。

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2017-01-06
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多