This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                6年前关闭。
            
                    
解决方案:错误是我的函数实际上是一个方法。

我正在尝试使用装饰器来模拟函数的变量。为什么在下面的最后一行出现此错误? global name 'onecmd' is not defined

def static_var(varname, initial_value):
  def decorate(func):
        setattr(func, varname, initial_value)
        return func
  return decorate

@static_var("last", None)
def onecmd(self, line):
    if line == "lastcmd":
        line = onecmd.last
    else:
        onecmd.last = line

最佳答案

您的代码似乎希望能够全局访问onecmd,但这是一种方法。在模块级别定义的函数确实可以通过其名称访问(因为它们存储为全局变量),但是类方法仅存储在类对象中。

您需要通过在其上定义此函数的类或通过self属性找到该函数对象,然后再返回该类,再返回该函数:

@static_var("last", None)
def onecmd(self, line):
    onecmd = type(self).onecmd.im_func  # im_func is the wrapped function
    if line == "lastcmd":
        line = onecmd.last
    else:
        onecmd.last = line


由于您已经有了一个类方法,因此最好将变量存储在类上:

class Foo(object):
    last = None

    def onecmd(self, line):
        if line == "lastcmd":
            line = type(self).last
        else:
            type(onecmd).last = line


甚至将其设置为类方法:

class Foo(object):
    last = None

    @classmethod
    def onecmd(cls, line):
        if line == "lastcmd":
            line = cls.last
        else:
            cls.last = line

关于python - 模拟函数的静态变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15481431/

10-12 00:22
查看更多