Class Python 2:类作用域

Class Python 2:类作用域,class,python-2.7,oop,python-decorators,Class,Python 2.7,Oop,Python Decorators,我编写了一个decorator,它将更改为用户提供的目录,执行一个函数,然后返回到原始目录 现在我试图在一个类中使用这个装饰器,但遇到了一个范围问题。这里有一个例子 class SampleClass(object): def __init__(self, working_dir): self.dir = working_dir @preserve_cwd(self.dir) def do_stuff(self): pass Pyt

我编写了一个decorator,它将更改为用户提供的目录,执行一个函数,然后返回到原始目录

现在我试图在一个类中使用这个装饰器,但遇到了一个范围问题。这里有一个例子

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

    @preserve_cwd(self.dir)
    def do_stuff(self):
        pass  
Python将返回名称错误:未定义名称“self”

在类的_uinit__;方法中定义属性并能够在类名空间中使用它们,有什么好方法吗?谢谢你的帮助

编辑:

注释请求装饰器定义

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

你应该把“ABC”印在“p!”的上面和下面。通过这种方式,您可以根据需要更改环境,然后将其恢复到以前的状态。

装饰器位于方法外部,而不是内部,这就是为什么没有定义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()

你应该把“ABC”印在“p!”的上面和下面。这样,您可以根据需要更改环境,然后将其恢复到以前的状态。

为什么不发布装饰器定义?我肯定会有帮助的。你为什么不发布装饰师的定义?我肯定会有帮助的。