使用定义为实例变量的装饰器函数

Cad*_*son 6 python decorator flask python-decorators

(虽然这个问题是关于Flask的,但可以根据标题推广)

我正在尝试在类中使用Flask的app.route()装饰器.但是,Flask应用程序初始化为实例变量,即self.server设置为app.这意味着我不能使用装饰器,因为self在装饰方法之外是未定义的.我希望能够做到以下几点:

class MyClass:

    def __init__(self):
        self.server = Flask(__name__)

    @self.server.route('/')
    def home():
        return '<h1>Success</h1>'
Run Code Online (Sandbox Code Playgroud)

这个问题有没有解决方法?任何帮助是极大的赞赏!

Ian*_*ney 3

您可以在方法的上下文中定义函数__init__。然后,为了使函数能够正常调用,将home成员设置为等于它。

class MyClass:
    def __init__(self):
        self.server = Flask(__name__)

        # This is indented at __init__'s level, so a new instance of the function
        # is defined every time __init__ runs. That means a new instance
        # is defined for each instance of the class, and so it can be wrapped with
        # the instance's "self" value.
        @self.server.route('/')
        def home_func():
            return '<h1>Success</h1>'

        # Then, you make it an object member manually:
        self.home = home_func
Run Code Online (Sandbox Code Playgroud)