Python 2: class 范围

Python 2: class scope

我写了一个装饰器,它将更改为用户提供的目录,执行一个函数,然后 return 到原始目录。

现在我正尝试在 class 中使用这个装饰器,但遇到了范围界定问题。这是一个例子。

class SampleClass(object):
    def __init__(self, working_dir):
        self.dir = working_dir

    @preserve_cwd(self.dir)
    def do_stuff(self):
        pass  

Python 将 return NameError: 名称 'self' 未定义

有没有什么好的方法可以在class的__init__方法中定义属性并能够在class名称space中使用它们?感谢您的帮助。

编辑:

评论要求装饰器定义。

def preserve_cwd(working_dir):
    """Decorator: Return to the current working directory after function call.

    :param str working_dir: path to working directory
    """
    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            original_dir = os.getcwd()
            os.chdir(working_dir)

            try:
                func(*args, **kwargs)
            finally:
                os.chdir(original_dir)

        return wrapped
    return decorator

装饰器在方法之外,而不是方法内部,这就是为什么没有定义 self 的原因。

你可以试试这样一段代码:

#define the decorator, it accepts the function to be wrapped
def dec(f):
    #it returns a function that takes some arguments
    def wrapper(*args):
        s, = args  #take the first one (it should be self)
        print(s.dir) #do something
        result = f(*args) #call the wrapped function
        print(s.dir) #do something
        return result #return the result of the function
    #and returns the wrapped function
    return wrapper

class A:
    def __init__(self, dir):
        self.dir = dir

    @dec
    def p(self):
        print "P!"

a = A("ABC")
a.p()

您应该在 "P!" 上方和下方打印 "ABC"。这样您就可以根据需要更改环境,然后将其恢复到以前的状态。